使用SpringBoot搭建WebSocket服務

1、springboot環境

在這裏插入圖片描述

2、加入websocket依賴

在這裏插入圖片描述

3、加入websocket配置類

在這裏插入圖片描述

4、添加websocket響應事件處理

ServerEndpoint(value = "/websocket/test/{sid}")
@Component
@Slf4j
public class WebSocketServer {
    /**
     * 每個客戶端對應的WebSocket對象
     */
    public static Map<String, Session> clientMap = new ConcurrentHashMap<>();

    /**
     * 連接建立成功調用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        clientMap.put(sid, session);

        log.info("有一個新的客戶端 : " + sid + " , 當前客戶端連接總數: " + clientMap.size());
        try {
            WebScoketHelper.sendMessage(session, "你好,新客戶端!sid = " + sid);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 連接關閉調用的方法
     */
    @OnClose
    public void onClose(@PathParam("sid") String sid) {
        clientMap.remove(sid);
        log.info("有一個客戶端斷開,當前客戶端連接總數: " + clientMap.size());
    }

    /**
     * 收到客戶端消息
     * @param message 客戶端發送過來的消息
     */
    @OnMessage
    public void onMessage(String message, @PathParam("sid") String sid) {
    	log.info("接收到客戶端消息, " + sid +" , message: " + message);
    }

	/**
	 * 
	 * @param session
	 * @param error
	 */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("出錯了!");
        error.printStackTrace();
    }

}

WebSocketHelper代碼:

@Slf4j
public class WebScoketHelper {

    /**
     * 推送文本消息給指定的客戶端
     */
    public static void sendMessage(Session sess, String message) throws IOException {
        sess.getBasicRemote().sendText(message);
    }

    /**
     * 推送對象給指定的客戶端
     * @param sess:
     * @param object:
     */
    public static void sendObject(Session sess, Object object) throws IOException, EncodeException {
            sess.getBasicRemote().sendObject(object);
    }

    /**
     * 推送文本給所有的客戶端
     */
    public static void sendTextToAll(Collection<Session> sessionList, String message) {

        sessionList.forEach(e -> {
            try {
                sendMessage(e, message);
            } catch (IOException e1 ) {
                throw new RuntimeException("推送失敗,session.id=" + e.getId(), e1);
            }
        });
    }

    /**
     * 推送文本給所有的客戶端
     */
    public static void sendObjectToAll(Collection<Session> sessionList, String message) {

        sessionList.forEach(e -> {
            try {
                sendObject(e, message);
            } catch (IOException | EncodeException e1) {
                throw new RuntimeException("推送失敗,session.id=" + e.getId(), e1);
            }
        });
    }

5、頁面js處理代碼

  //websocket握手
    var socket;
    if(typeof(WebSocket) == "undefined") {
        console.log("Your browser is not support WebSocket!");
    }else{
        console.log("Your browser is ok for WebSocket!");

        //建立連接
        socket = new WebSocket("ws://localhost:18080/websocket/test/123");
        socket.onopen = function() {
            console.log("Socket is open!");
        };

        //獲得消息事件
        socket.onmessage = function(msg) {        
            console.log("瀏覽器推來消息:" + msg.data);
            
        };

        //關閉事件
        socket.onclose = function() {
            console.log("Socket 關閉了!");
        };

        //發生了錯誤事件
        socket.onerror = function() {
            alert("Socket 出錯了!");
        }

    }

此時,websocket服務已基本開發成功,打開瀏覽器,輸入:http://localhost:18080/,查看瀏覽器控制檯:在這裏插入圖片描述
打開postman, 發送請求:http://localhost:18080/send, 結果如下圖:在這裏插入圖片描述
至此,websocket測試成功!

6、編碼

上面的websocket服務,推送文本、字符串是正常了,但是推送對象會報錯。如下:在這裏插入圖片描述
提示很明確,沒有定義編碼器,下面我們來自定義一個編碼器。

public class ObjectMessageEncoder implements Encoder.Text<Object> {

    @Override
    public String encode(Object message) throws EncodeException {
        try {
            return mapper.writeValueAsString(message);
        } catch (JsonProcessingException e) {
            throw new EncodeException(e, "encode faliure!");
        }
    }

    @Override
    public void init(EndpointConfig endpointConfig) {

    }

    @Override
    public void destroy() {

    }

    protected static ObjectMapper mapper = new ObjectMapper();
}

配置編碼器,在服務代碼上修改:
在這裏插入圖片描述
再次測試發送對象,已經正常推送了。

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