java websocket入門

1. 結果展示

2. WebSocketConfig

package com.sadhu.websocket.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * @ClassName WebSocketConfig
 * @Description 首先要注入ServerEndpointExporter,這個bean會自動註冊使用了@ServerEndpoint註解聲明的Websocket endpoint。
 *              要注意,如果使用獨立的servlet容器,而不是直接使用springboot的內置容器,就不要注入ServerEndpointExporter,
 *              因爲它將由容器自己提供和管理。
 * @Author sadhu
 * @Date 2021/11/10 13:26
 **/
@Configuration
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

3. WebSocketConfigurator

package com.sadhu.websocket.config;

import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;

/**
 * @ClassName WebSocketConfigurator
 * @Description TODO 在握手期間發送自定義標頭,使用ServerEndpointConfig.Configurator攔截握手並覆蓋modifyHandshake
 * @Author sadhu
 * @Date 2021/11/10 13:34
 **/
public class WebSocketConfigurator extends ServerEndpointConfig.Configurator {
    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        //TODO request分割參數獲取token,或者從header中直接獲取token
        super.modifyHandshake(sec, request, response);
    }
}

4. WebSocketServer

package com.sadhu.websocket;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sadhu.websocket.config.WebSocketConfigurator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName WebSocketServer
 * @Description TODO
 * @Author sadhu
 * @Date 2021/11/10 13:26
 **/
@Component
@ServerEndpoint(value = "/websocket/{token}", configurator = WebSocketConfigurator.class)
@Slf4j
public class WebSocketServer {
    /**
     * 用來存放每個客戶端的session連接,線程安全
     */
    private static ConcurrentHashMap<String, Session> webSocketMap = new ConcurrentHashMap<>();


    @OnOpen
    public void OnOpen(Session session, EndpointConfig config, @PathParam("token") String token) throws IOException {
        //TODO config.getUserProperties().get("token") 對這裏的token進行判斷

        //請求url上帶token,這邊只是模擬,方便測試
        if (StringUtils.isEmpty(token)) {
            session.close();
            return;
        }

        if (webSocketMap.contains(token)) {
            webSocketMap.get(token).close(); //以防萬一,一般token不會重複
        }
        webSocketMap.put(token, session);
        log.info("[websocket]連接成功,當前連接數爲: {}", webSocketMap.size());
    }

    @OnClose
    public void OnClose(@PathParam("token") String token) {
        webSocketMap.remove(token);
        log.info("[websocket]退出成功,當前連接數爲: {}", webSocketMap.size());
    }

    @OnMessage
    public void OnMessage(Session session, String message) {
        message = "客戶端:" + message + ",已收到";
        log.info("[websocket]接收到客戶端[{}]的message => {}", session.getId(), message);
        try {
            sendMessage(session, message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("發生錯誤");
        throwable.printStackTrace();
    }


    /**
     * 發送信息
     *
     * @param session
     * @param message
     * @throws IOException
     */
    private static void sendMessage(Session session, String message) throws IOException {
        if (session != null) {
            synchronized (session) {
                session.getBasicRemote().sendText(message);
            }
        }
    }

    /**
     * 指定用戶發送
     *
     * @param token
     * @param message
     */
    public static void sendByToken(String token, String message) {
        Session session = webSocketMap.get(token);
        JSONObject json = JSONUtil.parseObj(message);
        json.setDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            sendMessage(session, json.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 羣發
     *
     * @param message
     */
    public static void sendByGroup(String message) {
        JSONObject json = JSONUtil.parseObj(message);
        json.setDateFormat("yyyy-MM-dd HH:mm:ss");
        webSocketMap.forEach((token, session) -> {
            try {
                sendMessage(session,json.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}

5. index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
websocket Demo------ <br />
<input id="text" type="text" />
<button onclick="send()"> Send </button>
<button   onclick="closeWebSocket()"> Close </button>
<div id="message">   </div>

<script type="text/javascript">
    //判斷當前瀏覽器是否支持WebSocket
    if('WebSocket' in window){
        //這裏修改url參數
        websocket = new WebSocket("ws://localhost:8888/websocket/1002");
        console.log("link success")
    }else{
        alert('Not support websocket')
    }

    //連接發生錯誤的回調方法
    websocket.onerror = function(){
        setMessageInnerHTML("error");
    };

    //連接成功建立的回調方法
    websocket.onopen = function(event){
        setMessageInnerHTML("open");
    }
    console.log("-----")
    //接收到消息的回調方法
    websocket.onmessage = function(event){
        setMessageInnerHTML(event.data);
    }

    //連接關閉的回調方法
    websocket.onclose = function(){
        setMessageInnerHTML("close");
    }

    //監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。
    window.onbeforeunload = function(){
        websocket.close();
    }

    //將消息顯示在網頁上
    function setMessageInnerHTML(innerHTML){
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //關閉連接
    function closeWebSocket(){
        websocket.close();
    }

    //發送消息
    function send(){
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>

</body>
</html>

6. pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>websocket</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.3.2.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!-- web模塊-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--日誌-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>


        <!--websocket支持-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.12</version>
        </dependency>
    </dependencies>
</project>

7. 羣發功能驗證


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章