1、在pom.xml文件中添加依賴
<dependency>
? ? <groupId>org.springframework.boot</groupId>
? ? <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2圈匆、WebSocketConfig
@Configuration
public class WebSocketConfig {
@Bean
? ? public ServerEndpointExporterserverEndpointExporter(){
return new ServerEndpointExporter();
? ? }
}
3馒过、WebSocketServer
@ServerEndpoint("/websocket")
@Component
public class WebSocketServer {
//靜態(tài)變量腹忽,用來記錄當(dāng)前在線連接數(shù)。應(yīng)該把它設(shè)計成線程安全的嘹锁。
? ? private static int onlineCount =0;
? ? //concurrent包的線程安全Set着裹,用來存放每個客戶端對應(yīng)的MyWebSocket對象。
? ? private static CopyOnWriteArraySetwebSocketSet =new CopyOnWriteArraySet();
? ? //與某個客戶端的連接會話摔竿,需要通過它來給客戶端發(fā)送數(shù)據(jù)
? ? private Sessionsession;
? ? /**
* 連接建立成功調(diào)用的方法
*/
? ? @OnOpen
? ? public void onOpen(Session session) {
this.session = session;
? ? ? ? webSocketSet.add(this);? ? //加入set中
? ? ? ? addOnlineCount();? ? ? ? ? //在線數(shù)加1
? ? ? ? System.out.println("有新窗口開始監(jiān)聽,當(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ā)送過來的消息
*/
? ? @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ā)生錯誤");
? ? ? ? error.printStackTrace();
? ? }
/**
* 實現(xiàn)服務(wù)器主動推送
*/
? ? 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;
? ? ? ? ? ? }
}
}
4袁翁、WebSocketController
@RestController
public class WebSocketController {
@RequestMapping("/socket")
public StringopenTencent(){
? ? ? ? return "tencent";
? ? }
/**
* 推送數(shù)據(jù)
? ? * @param say
? ? * @return
? ? */
? ? @RequestMapping("/socket/push")
public StringpushMsg(@RequestParam("say") String say) {
try {
WebSocketServer.sendInfo("服務(wù)器推送消息"+say);
? ? ? ? }catch (IOException e) {
e.printStackTrace();
? ? ? ? }
return "tencent";
? ? }
}
5粱胜、index
<!DOCTYPE html>
<html lang="en">
? ? <meta charset="UTF-8">
? ? <title>WebSocket頁面
<div style="margin-left:400px;width:500px;height:120px;background-color:wheat">
? ? <h2>請輸入想說的話:
? ? <input type="text" id="say" name="say">
? ? <input type="button" id="sendSay" name="sendSay" value="發(fā)送">
<div style="margin-left:400px;">
? ? <h2>對話框
? ? <textarea id="message" cols="150px" rows="200px" disabled style="width:500px;height:500px">
? ? var socket;
? ? var say = document.getElementById("say");
? ? var sendSay = document.getElementById("sendSay");
? ? var message= document.getElementById("message");
? ? if (typeof(WebSocket) =="undefined") {
console.log("您的瀏覽器不支持WebSocket");
? ? }else {
console.log("您的瀏覽器支持WebSocket");
? ? ? ? //實現(xiàn)化WebSocket對象焙压,指定要連接的服務(wù)器地址與端口建立連接
? ? ? ? socket =new WebSocket("ws://localhost:8080/websocket");
? ? ? ? //打開事件
? ? ? ? socket.onopen =function () {
console.log("Socket已打開");
? ? ? ? ? ? // socket.send("這是來自客戶端的消息:" + new Date());
? ? ? ? };
? ? ? ? sendSay.onclick =function sendSay(){
socket.send("這是來自客戶端的消息:" + say.value)
};
? ? ? ? //獲得消息事件
? ? ? ? socket.onmessage =function (msg) {
console.log(msg.data);
? ? ? ? ? ? // alert(msg.data);
? ? ? ? ? ? var messageInfo = message.value;
? ? ? ? ? ? messageInfo = messageInfo +" \n " + msg.data;
? ? ? ? ? ? message.value = messageInfo;
? ? ? ? };
? ? ? ? //關(guān)閉事件
? ? ? ? socket.onclose =function () {
console.log("Socket已關(guān)閉");
? ? ? ? };
? ? ? ? //發(fā)生了錯誤事件
? ? ? ? socket.onerror =function () {
alert("Socket發(fā)生了錯誤");
? ? ? ? }
}
</html>