Spring Boot WebSocket
1. SpringBoot2對WebSocket的支援很贊
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2. WebSocketConfig
package com.springboot.websocket.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
importorg.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3.WebSocketServer
因為WebSocket是類似客戶端服務端的形式(採用ws協議),那麼這裡
的WebSocketServer其實就相當於一個ws協議的Controller
直接@ServerEndpoint(“/websocket”)@Component啟用即可,然後在
裡面實現@OnOpen,@onClose,@onMessage等方法
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 {
//靜態變數,用來記錄當前線上連線數。應該把它設計成執行緒安全的。
private static int onlineCount = 0;
//concurrent包的執行緒安全Set,用來存放每個客戶端對應的MyWebSocket物件。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//與某個客戶端的連線會話,需要通過它來給客戶端傳送資料
private Session session;
/**
* 連線建立成功呼叫的方法
*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //線上數加1
System.out.println("有新視窗開始監聽,當前線上人數為" + getOnlineCount());
try {
sendMessage("連線成功");
} catch (IOException e) {
System.out.println("WebSocket IO異常");
}
}
/**
* 連線關閉呼叫的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //從set中刪除
subOnlineCount(); //線上數減1
System.out.println("有連線關閉!當前線上人數為" + getOnlineCount());
}
/**
* 收到客戶端訊息後呼叫的方法
*
* @param message 客戶端傳送過來的訊息
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("收到客戶端的資訊:" + message);
//群發訊息
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("發生錯誤");
error.printStackTrace();
}
/**
* 實現伺服器主動推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群發自定義訊息
*/
public static void sendInfo(String message) throws IOException {
System.out.println("推送訊息內容:" + 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--;
}
}
4.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 {
//推送資料介面 @RequestMapping("/socket/push")
public String pushMsg(String message) {
try {
WebSocketServer.sendInfo(message);
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
}
5.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");
//實現化WebSocket物件,指定要連線的伺服器地址與埠建立連線
socket = new WebSocket("ws://localhost:8080/websocket");
//開啟事件
socket.onopen = function () {
console.log("Socket已開啟");
socket.send("這是來自客戶端的訊息:" + new Date());
};
//獲得訊息事件
socket.onmessage = function (msg) {
console.log(msg);
alert(msg);
};
//關閉事件
socket.onclose = function () {
console.log("Socket已關閉");
};
//發生了錯誤事件
socket.onerror = function () {
alert("Socket發生了錯誤");
}
}
</script>
</body>
</html>
6. 執行截圖
相關文章
- Spring Boot系列22 Spring Websocket實現websocket叢集方案的DemoSpring BootWeb
- Spring Boot系列21 Spring Websocket實現websocket叢集方案討論Spring BootWeb
- spring boot +WebSocket 廣播式例項Spring BootWeb
- Spring Boot系列十七 Spring Boot 整合 websocket,使用RabbitMQ做為訊息代理Spring BootWebMQ
- Spring Boot系列十六 WebSocket簡介和spring boot整合簡單訊息代理Spring BootWeb
- Spring Boot 整合單機websocket(附github原始碼)Spring BootWebGithub原始碼
- 在Spring Boot中實現WebSocket實時通訊Spring BootWeb
- Spring Boot中使用WebSocket總結(三):使用訊息佇列實現分散式WebSocketSpring BootWeb佇列分散式
- 使用Spring Boot排程WebSocket推送的教程和原始碼 - BaeldungSpring BootWeb原始碼
- Spring整合WebSocketSpringWeb
- Spring Boot系列20 Spring Websocket實現向指定的使用者傳送訊息Spring BootWeb
- Spring Boot:Spring Boot配置MybatisSpring BootMyBatis
- Spring Boot:Spring Boot配置SwaggerSpring BootSwagger
- Spring Boot 開發整合 WebSocket,實現私有即時通訊系統Spring BootWeb
- Spring Boot 整合 WebSocket 實現服務端推送訊息到客戶端Spring BootWeb服務端客戶端
- spring、spring MVC、spring BootMVCSpring Boot
- Spring Boot系列十九 Spring boot整合 swaggerSpring BootSwagger
- Spring Boot 參考指南(Spring Boot文件)Spring Boot
- Spring Boot 2.0(八):Spring Boot 整合 MemcachedSpring Boot
- Spring Boot —— Spring SecuritySpring Boot
- Spring BootSpring Boot
- Jeecg-Boot Spring BootSpring Boot
- Spring boot學習(三) Spring boot整合mybatisSpring BootMyBatis
- Spring boot學習(四)Spring boot整合DruidSpring BootUI
- Spring Boot系列(一):Spring Boot快速開始Spring Boot
- Spring Boot系列(四):Spring Boot原始碼解析Spring Boot原始碼
- Spring Boot系列(一):Spring Boot 入門篇Spring Boot
- Spring Boot 2.0(四):使用 Docker 部署 Spring BootSpring BootDocker
- Spring Boot學習(一)——Spring Boot介紹Spring Boot
- Spring Boot整合Spring SecuritySpring Boot
- Spring Boot整合Spring BatchSpring BootBAT
- Spring Boot整合Spring AopSpring Boot
- Spring boot學習(一)開啟Spring boot之旅Spring Boot
- Spring boot學習(二) Spring boot基礎配置Spring Boot
- Spring Boot入門(一):搭建Spring Boot專案Spring Boot
- Spring Boot(十二):Spring Boot 如何測試打包部署Spring Boot
- Spring Boot學習筆記:Spring Boot核心配置Spring Boot筆記
- Spring Boot2 系列教程(三)理解 Spring BootSpring Boot