Spring Boot 系列 - WebSocket 簡單使用


在實現消息推送的項目中往往需要WebSocket,以下簡單講解在Spring boot 中使用 WebSocket。

1、pom.xml 中引入 spring-boot-starter-websocket

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

2、往spring容器中注入 ServerEndpointExporter

package com.sam.conf;

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

/**
 * WebSocket配置
 * <p>
 * 自動注冊使用了@ServerEndpoint注解聲明的Websocket endpoint
 * 要注意,如果使用獨立的servlet容器,而不是直接使用springboot的內置容器,就不要注入ServerEndpointExporter,因為它將由容器自己提供和管理。
 *
 * @author sam
 * @since 2017/9/13
 */

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

}

3、Endpoint 具體實現

package com.sam.websocket;

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.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * ServerEndpoint
 * <p>
 * 使用springboot的唯一區別是要@Component聲明下,而使用獨立容器是由容器自己管理websocket的,但在springboot中連容器都是spring管理的。
 * <p>
 * 雖然@Component默認是單例模式的,但springboot還是會為每個websocket連接初始化一個bean,所以可以用一個靜態set保存起來。
 *
 * @author sam
 * @since 2017/9/13
 */
@ServerEndpoint("/ws/chatRoom/{userName}") //WebSocket客戶端建立連接的地址
@Component
public class ChatRoomServerEndpoint {

    /**
     * 存活的session集合(使用線程安全的map保存)
     */
    private static Map<String, Session> livingSessions = new ConcurrentHashMap<>();

    /**
     * 建立連接的回調方法
     *
     * @param session  與客戶端的WebSocket連接會話
     * @param userName 用戶名,WebSocket支持路徑參數
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userName") String userName) {
        livingSessions.put(session.getId(), session);
        sendMessageToAll(userName + " 加入聊天室");
    }

    /**
     * 收到客戶端消息的回調方法
     *
     * @param message 客戶端傳過來的消息
     * @param session 對應的session
     */
    @OnMessage
    public void onMessage(String message, Session session, @PathParam("userName") String userName) {
        sendMessageToAll(userName + " : " + message);
    }


    /**
     * 發生錯誤的回調方法
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("發生錯誤");
        error.printStackTrace();
    }

    /**
     * 關閉連接的回調方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("userName") String userName) {
        livingSessions.remove(session.getId());
        sendMessageToAll(userName + " 退出聊天室");
    }


    /**
     * 單獨發送消息
     *
     * @param session
     * @param message
     */
    public void sendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 群發消息
     *
     * @param message
     */
    public void sendMessageToAll(String message) {
        livingSessions.forEach((sessionId, session) -> {
            sendMessage(session, message);
        });
    }

}

4、前端頁面實現

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天室</title>
    <script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
</head>
<body>
<h1>聊天室</h1>

<textarea id="chat_content" readonly="readonly" cols="100" rows="9">

</textarea>

<br>

用戶:<input type="text" id="user_name" value="" name="userName"/>
<button id="btn_join">加入聊天室</button>
<button id="btn_exit">退出聊天室</button>

<br>

消息:<input type="text" id="send_text" value="" name="sendText"/>
<button id="btn_send">發送</button>

</body>
</html>

<script>
    $(function () {

        var prefixUrl = 'ws://127.0.0.1:8080/ws/chatRoom/';

        var ws;//WebSocket連接對象

        //判斷當前瀏覽器是否支持WebSocket
        if (!('WebSocket' in window)) {
            alert('Not support websocket');
        }

        $('#btn_join').click(function () {

            var userName = $('#user_name').val();

            //創建WebSocket連接對象
            ws = new WebSocket(prefixUrl + userName);

            //連接成功建立的回調方法
            ws.onopen = function (event) {
                console.log('建立連接')
            }

            //接收到消息的回調方法
            ws.onmessage = function (event) {
                console.log('接收到內容:' + event.data)
                $('#chat_content').append(event.data + '\n')
            }

            //連接發生錯誤的回調方法
            ws.onerror = function (event) {
                console.log('發生錯誤')
            }

            //連接關閉的回調方法
            ws.onclose = function (event) {
                console.log('關閉連接')
            }

        })

        //發送消息
        function sendMessage(message) {
            ws.send(message);
        }

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

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


        //發送消息
        $('#btn_send').click(function () {
            sendMessage($('#send_text').val())
        })

        //點擊退出聊天室
        $('#btn_exit').click(function () {
            closeWebSocket();
        })
    })
</script>

以上為完整demo內容。

推薦: 阿里技術-小馬哥講解WebSocket


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM