1. 程式人生 > 其它 >WebSocket乾貨-1

WebSocket乾貨-1

首先Maven依賴

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

自動配置

@Configuration
public class SocketClientConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        
return new ServerEndpointExporter(); } }
ServerEndpointExporter   翻譯過來是伺服器端點匯出器 具體是做什麼不知道 就當是自動注入需要的配置類吧

千呼萬喚使出來 -ServerEndpoint

   這個就是埠服務了 先貼程式碼

@ServerEndpoint("/client/{sid}")
public class ISocketClientService {
    private static  Integer onCount=0;
    private Session session;
    
private String sid; private static CopyOnWriteArraySet<ISocketClientService> webSocketSet = new CopyOnWriteArraySet<ISocketClientService>(); /** * 連線成功建立的方法 * @param session * @param sid */ @OnOpen public void onOpen(Session session, @PathParam("sid")String sid){
this.session=session; this.sid=sid; webSocketSet.add(this); log.info("有新視窗開始監聽:"+sid+",當前線上人數為" + ++onCount); try { this.session.getBasicRemote().sendText("登入成功. 當前賬戶sid為:"+this.sid); } catch (IOException e) { log.error("訊息傳送出錯"); e.printStackTrace(); }finally { } } @OnClose public void onClose(){ webSocketSet.remove(this); //從set中刪除 --onCount; //線上數減1 log.info("有一連線關閉!當前線上人數為" + onCount); } @OnMessage public void OnMessage(String message, Session session){ log.info("收到來自視窗"+sid+"的資訊:"+message); } @OnError public void onError(Session session, Throwable error) { log.error("發生錯誤"); error.printStackTrace(); } public void sendMsg(String messagem,String sid){ //判斷sid是否存在 try { this.session.getBasicRemote().sendText(this.sid); } catch (IOException e) { e.printStackTrace(); } } }

前端JS呼叫

<script>
    var sockest;
    if(typeof(WebSocket) == "undefined") {
        console.log("您的瀏覽器不支援WebSocket");
    }else{
        console.log("您的瀏覽器支援WebSocket");
        //實現化WebSocket物件,指定要連線的伺服器地址與埠  建立連線
        //等同於
        index = new WebSocket("ws://localhost:8823/client/2");
        sockest=index;
        //socket = new WebSocket("${basePath}websocket/${cid}".replace("http","ws"));
        //開啟事件
        index.onopen = function() {
            console.log("Socket 已開啟");
            //socket.send("這是來自客戶端的訊息" + location.href + new Date());
        };
        //獲得訊息事件
        index.onmessage = function(msg) {
            console.log(msg.data);
            //發現訊息進入    開始處理前端觸發邏輯
        };
        //關閉事件
        index.onclose = function() {
            console.log("Socket已關閉");
        };
        //發生了錯誤事件
        index.onerror = function() {
            alert("Socket發生了錯誤");
            //此時可以嘗試重新整理頁面
        }
        //離開頁面時,關閉socket
        //jquery1.8中已經被廢棄,3.0中已經移除
        // $(window).unload(function(){
        //     socket.close();
        //});
    }



    function sendMsg() {


        console.log("sendmsg");
        this.sockest.send("頁面傳送來資料了 快接收啊。")
    }
</script>

  

至此一個WebSocket的框子就搭好了

  下一步實現

      1對1聊天

      多人聊天