Spring集成websocket全流程

因爲我們是spring+mvc的項目所以還是需要websocket的maven配置

        <!-- WebSocket配置開始-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-websocket</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-messaging</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.websocket</groupId>
            <artifactId>javax.websocket-api</artifactId>
            <version>1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.3.1</version>
        </dependency>
        <!-- WebSocket配置結束-->

maven配置完成。注意spring.version得是4.0以上版本的

接下來這裏我用的是配置文件配置websocket

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:websocket="http://www.springframework.org/schema/websocket"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/websocket
       http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd">

    <bean id="websocket" class="com.lg.webapi.websocket.WebSocketService" />
    //這個是你的websocket服務,文件路徑用你自己的

    <!--<websocket:handlers>-->
        <!--<websocket:mapping path="/websocket" handler="websocket" />-->
        <!--<websocket:handshake-interceptors>-->
            <!--<bean class="com.lg.webapi.handle.MyHandshakeInterceptor" />-->
        <!--</websocket:handshake-interceptors>-->
    <!--</websocket:handlers>-->
    //這裏我去掉了攔截器
</beans>

ok配置完了。然後引入到spring的配置文件裏

首先在spring的配置文件頂部加入

xmlns:websocket="http://www.springframework.org/schema/websocket"

然後引入

<import resource="spring-websocket.xml"/>

上面兩步就完成了,然後編寫websocketService,這個服務是基於我的需求來的,你們自己改自己的需求,但是大體邏輯是不變的。@ServerEndpoint("/websocket/chat/{roomName}/{userName}")這個就相當於controller中的reqestMapping。後面就是請求這個url然後就能通訊了

/**
 * @author fish
 */
@ServerEndpoint("/websocket/chat/{roomName}/{userName}")
public class WebSocketService{

    private static final Logger logger = Logger.getLogger(WebSocketService.class);

    // 使用map來收集session,key爲roomName,value爲同一個房間的用戶集合
    // concurrentMap的key不存在時報錯,不是返回null
    private static final Map<String, Set<Session>> rooms = new ConcurrentHashMap();
    private static final Map<String, String> userNameList = new ConcurrentHashMap();

    @OnOpen
    public void connect(@PathParam("roomName") String roomName, @PathParam("userName") String userName, Session session) throws Exception {
        // 將session按照房間名來存儲,將各個房間的用戶隔離
        if (!rooms.containsKey(roomName)) {
            // 創建房間不存在時,創建房間
            Set<Session> room = new HashSet<Session>();
            // 添加用戶
            room.add(session);

            rooms.put(roomName, room);
        } else {
            // 房間已存在,直接添加用戶到相應的房間
            rooms.get(roomName).add(session);
        }
        System.err.println("userName"+userName);
        System.out.println("a client has connected!");
    }

    @OnClose
    public void disConnect(@PathParam("roomName") String roomName,@PathParam("userName") String userName, Session session) {
        rooms.get(roomName).remove(session);
        System.out.println("a client has disconnected!");
    }

    @OnMessage
    public void receiveMsg(@PathParam("roomName") String roomName,@PathParam("userName") String userName,
                           String msg, Session session) throws Exception {
        // 此處應該有html過濾
        msg = userName + ":" + msg;
        // 接收到信息後進行廣播
        broadcast(roomName, msg);
    }

    // 按照房間名進行廣播
    public static void broadcast(String roomName, String msg) throws Exception {
        for (Session session : rooms.get(roomName)) {
            session.getBasicRemote().sendText(msg);
        }
    }

}

到這一步服務端的工作基本完成了。然後編寫一個前端頁面測試一下

注意 websocket = new WebSocket("ws://127.0.0.1:8088/app/websocket/chat/房間號/用戶暱稱"); 這行代碼根據你自己的項目地址修改。

<%@ page language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>index Page</title>
</head>
<body>
Welcome<br/><input id="text" type="text"/>
<button onclick="send()">發送消息</button>
<hr/>
<button onclick="closeWebSocket()">關閉WebSocket連接</button>
<hr/>
<div id="message"></div>
<table id="tb" class="altrowstable">
    <th align="center"  colspan="9">實時信息監控</th>
</table>
</body>

<script type="text/javascript">
    var websocket = null;
    //判斷當前瀏覽器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://127.0.0.1:8088/app/websocket/chat/房間1/啦啦啦");
    }
    else {
        alert('當前瀏覽器 Not support websocket')
    }

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

    //連接成功建立的回調方法
    websocket.onopen = function () {
        setMessageInnerHTML("WebSocket連接成功");
    }

    //接收到消息的回調方法
    websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data);
    }

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

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

    //將消息顯示在網頁上
    function setMessageInnerHTML(innerHTML) {
        var msg=innerHTML.split(" - ")

        var table=document.getElementById("tb");

        var row;
        row=table.insertRow(1);
        for(var i=0;i<msg.length;i++){
            var cell = row.insertCell(i);
            cell.appendChild(document.createTextNode(msg[i]));
        }
        if(table.rows.length>50){
            table.deleteRow(table.rows.length-1);
        }
        //  document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

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

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

好了一個websocket就配置完成了

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