spring boot websocket

1、對(duì)websocket的認(rèn)識(shí)

  實(shí)時(shí)性、雙工通信、走websocket(ws)協(xié)議不是HTTP、“拉和推”的概念,股票、石墨文檔多方在線協(xié)作、智能家居、賽況更新

2、什么是websocket

    WebSocket協(xié)議是基于TCP的一種新的網(wǎng)絡(luò)協(xié)議。它實(shí)現(xiàn)了瀏覽器與服務(wù)器全雙工(full-duplex)通信——允許服務(wù)器主動(dòng)發(fā)送信息給客戶端。
websocket.png

3、為什么需要websocket

   我們已經(jīng)有了 HTTP 協(xié)議,為什么還需要另一個(gè)協(xié)議?它能帶來(lái)什么好處?
  • 答案很簡(jiǎn)單,因?yàn)?HTTP 協(xié)議有一個(gè)缺陷:通信只能由客戶端發(fā)起,HTTP 協(xié)議做不到服務(wù)器主動(dòng)向客戶端推送信息。
    舉例來(lái)說(shuō),我們想要查詢當(dāng)前的排隊(duì)情況,只能是頁(yè)面輪詢向服務(wù)器發(fā)出請(qǐng)求,服務(wù)器返回查詢結(jié)果。輪詢的效率低,非常浪費(fèi)資源(因?yàn)楸仨毑煌_B接,或者 HTTP 連接始終打開(kāi))。因此WebSocket 就是這樣發(fā)明的。

4、SpringBoot2對(duì)WebSocket的支持很贊

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

5、WebSocketConfig

package com.springboot.websocket.config;

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

/**
 * 開(kāi)啟WebSocket支持
 *
 * @author Moqi
 */
@Configuration
public class WebSocketConfig {

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

}

6、WebSocketServer

package com.springboot.websocket.config;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;


@ServerEndpoint("/websocket")
@Component
public class WebSocketServer {

    //靜態(tài)變量,用來(lái)記錄當(dāng)前在線連接數(shù)。應(yīng)該把它設(shè)計(jì)成線程安全的。
    private static int onlineCount = 0;
    //concurrent包的線程安全Set,用來(lái)存放每個(gè)客戶端對(duì)應(yīng)的MyWebSocket對(duì)象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    //與某個(gè)客戶端的連接會(huì)話,需要通過(guò)它來(lái)給客戶端發(fā)送數(shù)據(jù)
    private Session session;


    /**
     * 連接建立成功調(diào)用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在線數(shù)加1
        System.out.println("有新窗口開(kāi)始監(jiān)聽(tīng),當(dāng)前在線人數(shù)為" + getOnlineCount());
        try {
            sendMessage("連接成功");
        } catch (IOException e) {
            System.out.println("WebSocket IO異常");
        }
    }

    /**
     * 連接關(guān)閉調(diào)用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //從set中刪除
        subOnlineCount();           //在線數(shù)減1
        System.out.println("有連接關(guān)閉!當(dāng)前在線人數(shù)為" + getOnlineCount());
    }

    /**
     * 收到客戶端消息后調(diào)用的方法
     *
     * @param message 客戶端發(fā)送過(guò)來(lái)的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("收到客戶端的信息:" + message);
        //群發(fā)消息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("發(fā)生錯(cuò)誤");
        error.printStackTrace();
    }

    /**
     * 實(shí)現(xiàn)服務(wù)器主動(dòng)推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 群發(fā)自定義消息
     */
    public static void sendInfo(String message) throws IOException {
        System.out.println("推送消息內(nèi)容:" + message);
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}

7、WebSocketController

package com.springboot.websocket.controller;

import com.springboot.websocket.config.WebSocketServer;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
public class WebSocketController {

    //推送數(shù)據(jù)接口    @RequestMapping("/socket/push")
    public String pushMsg(String message) {
        try {
            WebSocketServer.sendInfo(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }
}

8、index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>
</head>
<body>
<h2>WebSocket</h2>
<script>
    var socket;
    if (typeof(WebSocket) == "undefined") {
        console.log("您的瀏覽器不支持WebSocket");
    } else {
        console.log("您的瀏覽器支持WebSocket");
        //實(shí)現(xiàn)化WebSocket對(duì)象,指定要連接的服務(wù)器地址與端口建立連接
        socket = new WebSocket("ws://localhost:8080/websocket");

        //打開(kāi)事件
        socket.onopen = function () {
            console.log("Socket已打開(kāi)");
            socket.send("這是來(lái)自客戶端的消息:" + new Date());
        };

        //獲得消息事件
        socket.onmessage = function (msg) {
            console.log(msg);
            alert(msg);
        };

        //關(guān)閉事件
        socket.onclose = function () {
            console.log("Socket已關(guān)閉");
        };

        //發(fā)生了錯(cuò)誤事件
        socket.onerror = function () {
            alert("Socket發(fā)生了錯(cuò)誤");
        }
    }
</script>

</body>
</html>
截圖.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容