SpringBoot學習(六)WebScoket應用

 

(一)、添加依賴(springboot)裏面整合的有WebScoket

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

(二)、創建配置類然後注入ServerEndpointExporter

ServerEndpointExporter會自動將使用了@ServerEndpoint註解的webscoket註冊進來。如果使用獨立的servlet容器,而不是直接使用springboot的內置容器,就不要注入ServerEndpointExporter,因爲它將由容器自己提供和管理

@Configuration
public class WebScoketConfig {

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

(三)、創建WebScoket類

@Slf4j
@Component
@ServerEndpoint("/webscoket")
public class WebSocket {

    //用來記錄當前在線連接數。增加減少連接數是線程同步的
    private static int onlineCount = 0;

    //每個連接通過他來傳遞消息:javax.websocket.Session
    private Session session;

    //每創建一個連接就會生成一個WebScoket,用CopyOnWriteArraySet進行保存
    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();

    //建立連接時自動調用
    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSockets.add(this);
        addOnlineCount();
        log.info("建立連接");
    }

    //連接關閉時自動調用
    @OnClose
    public void onClose(){
        webSockets.remove(this);
        subOnlineCount();
        log.info("斷開連接");
    }

    //收到消息時自動調用
    @OnMessage
    public void onMess(String mess){
        log.info("收到客戶端發來的消息"+mess);
    }

    //服務器發送消息的方法
    public  void sendMess(String mess){
        for(WebSocket webSocket : webSockets){
            log.info("{}發送消息是:{}",webSocket,mess);

            try {
                //發送消息
                webSocket.session.getBasicRemote().sendText(mess);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

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

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

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

}



在別的地方調用sendMess() 發送消息
{
    webSocket.sendMess("新消息");
}

(四)、客戶端接受消息


    var webScoket = null;
    //判斷瀏覽器是否支持webscoket
    if ("WebSocket" in window){
    //初始化webscoket
        webScoket = new WebSocket("ws://localhost:8081/sell/webscoket")
    }else {
        alert("該瀏覽器不支持webscoket")
    }

    webScoket.onopen = function (event) {
        console.log("建立連接")
    }

    webScoket.onclose = function (event) {
        console.log("關閉鏈接")
    }

    webScoket.onmessage = function (event) {
        console.log("收到消息"+event.data);
        alert(event.data)

    }
    webScoket.onerror = function (event) {
        console.log("發生錯誤")
    }
    //關閉窗口時斷開連接關閉webscoket
    window.onbeforeunload = function (ev) {
        webScoket.close();
    }

 

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