基於springmvc的websocket的配置


由於學東西有點慢,所以特將其詳細寫出:

共分為:web.xml的編寫,xmlspringweb-servlet.xml,前端的編寫,后台的編寫,四個部分

 

首先將所需的包列出,其中包括了所有的springmvc所需要的包:

 

1.這個工程的路徑圖片示意:

2.配置文件,web.xml的編寫

2.對應的xmlspringweb-servlet.xml的編寫:

 3.前端的編寫:

<!DOCTYPE HTML>
<html> 
    <head>
        <title>首頁</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="renderer" content="webkit"> 
        <!-- 引入 JQuery  -->
        <script type="text/javascript" src="jquery-3.3.1.min.js"></script> 
        <!-- 引入 sockJS  -->
       <script type="text/javascript" src="sockjs.min.js" ></script> 
        <!-- 自定義JS文件 -->
        <script >
            var url='ws://'+window.location.host+"/xmlspringweb/websocket";
            var websocket=new WebSocket(url);             
            // 打開時
            websocket.onopen = function(evnt) {
                console.log("  websocket.onopen  ");
            };
            // 處理消息時
            websocket.onmessage = function(evnt) {
                $("#msg").append("<p>(<font color='red'>" + evnt.data + "</font>)</p>");
                console.log("  websocket.onmessage   ");
            };         
            websocket.onerror = function(evnt) {
                console.log("  websocket.onerror  ");
            };         
            websocket.onclose = function(evnt) {
                console.log("  websocket.onclose  ");
            };                  
            // 點擊了發送消息按鈕的響應事件
            $("#TXBTN").click(function(){         
                // 獲取消息內容
                var text = $("#tx").val();         
                // 判斷
                if(text == null || text == ""){
                    alert(" content  can not empty!!");
                    return false;
                }         
                var msg = {
                    msgContent: text,
                    postsId: 1
                };         
                // 發送消息
                websocket.send(JSON.stringify(msg));
         
            });        
        </script> 
    </head> 
    <body>
        <!-- 最外邊框 -->
        <div style="margin: 20px auto; border: 1px solid blue; width: 300px; height: 500px;"> 
            <!-- 消息展示框 -->
            <div id="msg" style="width: 100%; height: 70%; border: 1px solid yellow;overflow: auto;"></div> 
            <!-- 消息編輯框 -->
            <textarea id="tx" style="width: 100%; height: 20%;"></textarea> 
            <!-- 消息發送按鈕 -->
            <button id="TXBTN" style="width: 100%; height: 8%;">發送數據</button> 
        </div>  
    </body> 
</html>

其中還需要兩個js文件:

jquery-3.3.1.min.js,sockjs.min.js(暫可不用,是為了兼容無法使用WebSocket而添加的,此前端並未體現)

 

4.后端程序,需要兩個程序,

1)Handler的編寫:

package springmvcdemo.web.controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class WebSocketHandle extends TextWebSocketHandler{ 

    private final static List<WebSocketSession> sessions = Collections.synchronizedList(new ArrayList<WebSocketSession>());
    //鎺ユ敹鏂囨湰娑堟伅錛屽苟鍙戦�佸嚭鍘�
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //chatTextMessageHandler(message.getPayload());
        super.handleTextMessage(session, message);
    }
    //榪炴帴寤虹珛鍚庡鐞�
    @SuppressWarnings("unchecked")
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("connect to the websocket chat success......");
        System.out.println(session.toString());
     
        sessions.add(session);
        //澶勭悊紱葷嚎娑堟伅
    }
    
    //鎶涘嚭寮傚父鏃跺鐞�
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if(session.isOpen()){
            session.close();
        }
        System.out.println("websocket chat connection closed......");
        sessions.remove(session);
    }
    
    //榪炴帴鍏抽棴鍚庡鐞�
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        System.out.println("websocket chat connection closed......");
        sessions.remove(session);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}

2)配置文件的編寫:

package springmvcdemo.web.controller;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
 
 
@Configuration
@EnableWebSocket
public class WebSocketConfig  implements WebSocketConfigurer {
 
        @Override
        public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
            System.out.println("....注冊......");
            //前台 可以使用websocket環境
           registry.addHandler(myWebSocketHandler(),"/websocket");
 
        } 
        // websocket 處理類
        @Bean
        public WebSocketHandler myWebSocketHandler(){
            return new WebSocketHandle();
        }
 
 
}

這樣整個的一個簡單的websocket的程序就寫完了。

 


免責聲明!

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



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