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

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);
});

