SpringBoot2集成WebSocket

依賴
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
新建WebSocketConfig
package com.wu.parker.websocket.config;

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

/**
 * @author: wusq
 * @date: 2018/12/10
 */
@Configuration
public class WebSocketConfig {

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

}

新建Controller
package com.wu.parker.websocket.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

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

/**
 * @author: wusq
 * @date: 2018/12/10
 */
@ServerEndpoint("/websocket/{token}")
@Component
public class WebSocketController {

    private static final Logger log = LoggerFactory.getLogger(WebSocketController.class);

    public static Map<String, Session> SESSION_MAP = new ConcurrentHashMap<>();

    /**
     * 連接建立成功調用的方法
     * @param session
     * @param token
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) {
        log.info("{}建立連接", token);
        SESSION_MAP.put(token, session);
        log.info("建立連接後session數量={}", SESSION_MAP.size());
        send(token, "Hello, connection opened!");
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        for(Map.Entry<String, Session> entry:SESSION_MAP.entrySet()){
            log.info("session.id={}", session.getId());
            if(session.getId().equals(entry.getValue().getId())){
                log.info("{}發來消息", entry.getKey());
            }
            break;
        }
        log.info("接收到消息:{}", message);

    }

    @OnClose
    public void onClose(Session session) {
        log.info("有連接關閉");
        Map<String, Session> map = new HashMap<>();
        SESSION_MAP.forEach((k, v) -> {
            if(!session.getId().equals(v.getId())){
                map.put(k, v);
            }
        });
        SESSION_MAP = map;
        log.info("斷開連接後session數量={}", SESSION_MAP.size());
    }

    void send(String token, String message){
        Session session = SESSION_MAP.get(token);
        if(session != null){
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.error("發送信息錯誤{}", e.getMessage());
                e.printStackTrace();
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("發生錯誤");
        error.printStackTrace();
    }

}

測試頁面
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>websocket通訊</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
    var socket;
    function openSocket() {
        if(typeof(WebSocket) == "undefined") {
            console.log("您的瀏覽器不支持WebSocket");
        }else{
            console.log("您的瀏覽器支持WebSocket");
            //實現化WebSocket對象,指定要連接的服務器地址與端口  建立連接
            //等同於socket = new WebSocket("ws://localhost:8080/xxxx/im/25");
            //var socketUrl="${request.contextPath}/im/"+$("#userId").val();
            var socketUrl="http://localhost:8080/websocket/"+$("#userId").val();
            socketUrl=socketUrl.replace("https","ws").replace("http","ws");
            console.log(socketUrl)
            socket = new WebSocket(socketUrl);
            //打開事件
            socket.onopen = function() {
                console.log("websocket已打開");
                //socket.send("這是來自客戶端的消息" + location.href + new Date());
            };
            //獲得消息事件
            socket.onmessage = function(msg) {
                console.log(msg.data);
                //發現消息進入    開始處理前端觸發邏輯
            };
            //關閉事件
            socket.onclose = function() {
                console.log("websocket已關閉");
            };
            //發生了錯誤事件
            socket.onerror = function() {
                console.log("websocket發生了錯誤");
            }
        }
    }
    function sendMessage() {
        if(typeof(WebSocket) == "undefined") {
            console.log("您的瀏覽器不支持WebSocket");
        }else {
            console.log("您的瀏覽器支持WebSocket");
            console.log('[{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}]');
            socket.send('[{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}]');
        }
    }
</script>
<body>
    <p>【userId】:<div><input id="userId" name="userId" type="text" value="1"></div>
    <p>【toUserId】:<div><input id="toUserId" name="toUserId" type="text" value="2"></div>
    <p>【toUserId】:<div><input id="contentText" name="contentText" type="text" value="這是信息"></div>
    <p>【操作】:<div><a onclick="openSocket()">開啓socket</a></div>
    <p>【操作】:<div><a onclick="sendMessage()">發送消息</a></div>
</body>

</html>
源代碼

https://github.com/wu-boy/parker.git
parker-websocket模塊

參考資料

SpringBoot2+WebSocket之聊天應用實戰(優化版本)

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