springboot的websocket配置demo

????????WebSocket是HTML5開始提供的一種瀏覽器與服務(wù)器間進行全雙工通訊的網(wǎng)絡(luò)技術(shù)。 WebSocket通信協(xié)議于2011年被IETF定為標準RFC 6455,WebSocketAPI被W3C定為標準。 在WebSocket API中,瀏覽器和服務(wù)器只需要要做一個握手的動作,然后,瀏覽器和服務(wù)器之間就形成了一條快速通道。兩者之間就直接可以數(shù)據(jù)互相傳送。

? ? ? ? 廢話不說上代碼:

項目的架構(gòu)如下圖:

項目結(jié)構(gòu)

springboot項目我就不說了! 使用IDEL工具非??焖俚木蛣?chuàng)建出來!

里面主要涉及三個類文件

===========BootSocketApplication類如下:=============

package com.uccc.cc;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

//@EnableWebSocket

@SpringBootApplication

public class BootSocketApplication {

? public static void main(String[] args) {

? ? ? SpringApplication.run(BootSocketApplication.class, args);

? }

}

==================然后是SocketServerEndpoint類:======================

package com.uccc.cc.socket;

import org.springframework.stereotype.Component;

import javax.websocket.*;

import javax.websocket.server.PathParam;

import javax.websocket.server.ServerEndpoint;

import java.io.IOException;

/**

* ServerEndpoint

*

* 使用springboot的唯一區(qū)別是要@Component聲明下,而使用獨立容器是由容器自己管理websocket的,但在springboot中連容器都是spring管理的。

*

* 雖然@Component默認是單例模式的,但springboot還是會為每個websocket連接初始化一個bean,所以可以用一個靜態(tài)set保存起來。

*

*/

@ServerEndpoint("/ws/chatRoom/{userName}") //WebSocket客戶端建立連接的地址

@Component

public class SocketServerEndpoint {

? ? /**

* 建立連接的回調(diào)方法

*

? ? * @param session? 與客戶端的WebSocket連接會話

? ? * @param userName 用戶名,WebSocket支持路徑參數(shù)

*/

? ? @OnOpen

? ? public void onOpen(Session session, @PathParam("userName") String userName) throws IOException {

? ? ? session.getBasicRemote().sendText("你好");

? ? }

? ? /**

* 收到客戶端消息的回調(diào)方法

*

? ? * @param message 客戶端傳過來的消息

? ? * @param session 對應(yīng)的session

*/

? ? @OnMessage

? ? public void onMessage(String message, Session session, @PathParam("userName") String userName) throws IOException {

? ? ? ? session.getBasicRemote().sendText(userName+"先生,輪到你發(fā)言了?");

? ? }

? ? /**

* 發(fā)生錯誤的回調(diào)方法

*

? ? * @param session

? ? * @param error

? ? */

? ? @OnError

? ? public void onError(Session session, Throwable error) {

? ? ? ? System.out.println("發(fā)生錯誤");

? ? ? ? error.printStackTrace();

? ? }

? ? /**

* 關(guān)閉連接的回調(diào)方法

*/

? ? @OnClose

? ? public void onClose(Session session, @PathParam("userName") String userName) {

}

}

==============接下來是配置類 WebSocketConfig======================
package com.uccc.cc;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration

public class WebSocketConfig {

? ? /**

* 使用@ServerEndpoint創(chuàng)立websocket endpoint

*

* 首先要注入ServerEndpointExporter,這個bean會自動注冊使用了@ServerEndpoint注解聲明的Websocket endpoint。要注意,如果使用獨立的servlet容器,而不是直接使用springboot的內(nèi)置容器,就不要注入ServerEndpointExporter,因為它將由容器自己提供和管理。

? ? * @return

? ? */

? ? @Bean

? ? public ServerEndpointExporter serverEndpointExporter() {

? ? ? ? return new ServerEndpointExporter();

? ? }

}

====================下面試一個html文件的前端的一段js===========


html的圖片

let url="ws://localhost:8080/ws/chatRoom/柳若松";

? ? const socket = new WebSocket(url);

// Connection opened

socket.addEventListener('open', function (event) {

? alert("鏈接成功")

? ? socket.send('Hello Server!');

});

socket.onerror=e=>{

alert("error")

}

// Listen for messages

socket.addEventListener('message', function (event) {

? ? console.log('Message from server', event.data);

});


測試步奏1


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

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

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評論 19 139
  • 1.1 spring IoC容器和beans的簡介 Spring 框架的最核心基礎(chǔ)的功能是IoC(控制反轉(zhuǎn))容器,...
    simoscode閱讀 6,846評論 2 22
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong閱讀 22,931評論 1 92
  • 第一回合: 12月26日晚十點多,號稱比特幣首富的李笑來發(fā)了一條微博: 撕逼事件第一回合開始。鄭伊廷何...
    易水寒_1b91閱讀 8,638評論 11 51
  • 由晴轉(zhuǎn)晴的『踐行』第6天作業(yè):《說說這些年,我們管理過的時間》 補作業(yè)~作業(yè)沒有按時完成,心里總惦記著。這幾天醫(yī)院...
    由晴轉(zhuǎn)晴閱讀 232評論 1 0

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