
最近使用SpringBoot集成WebSocket做了一個極簡的項目,主要應(yīng)對服務(wù)器主動向客戶端推送消息這種應(yīng)用場景,而且要保證消息的實時性,有一對一,也有一對多的場景。先記錄一下SpringBoot是如何集成WebSocket的吧,來一個極簡的demo,簡單到自己接收自己發(fā)送的信息。
demo搭建環(huán)境說明:
SpringBoot 2.1.4
thmeleaf
WebSocket
首先,需要在pom中導(dǎo)入必須的架包;
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- springboot和websocket的集成 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
第二步,添加WebSocket的配置文件;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* websocket配置文件配置
* @author 程就人生
* @date 2019年9月23日
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
第三步,WebSocket服務(wù)端功能的開啟,信息的接收、發(fā)送、關(guān)閉;
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.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* websocket聊天信息的接收處理,最簡單的demo
* @author 程就人生
* @date 2019年9月24日
* @Description
*
*/
@ServerEndpoint("/websocket1")
@Component
public class WebSocketServer1 {
private static Logger log = LoggerFactory.getLogger(WebSocketServer1.class);
//concurrent包的線程安全Set,用來存放每個客戶端對應(yīng)的MyWebSocket對象。
private static CopyOnWriteArraySet<WebSocketServer1> webSocketSet = new CopyOnWriteArraySet<WebSocketServer1>();
/**
* 連接建立成功調(diào)用的方法
*/
@OnOpen
public void onOpen(Session session) {
//加入set中
webSocketSet.add(this);
log.info("有新連接加入!當(dāng)前在線人數(shù)為" + webSocketSet.size());
}
/**
* 連接關(guān)閉調(diào)用的方法
*/
@OnClose
public void onClose() {
//從set中刪除
webSocketSet.remove(this);
log.info("有一連接關(guān)閉!當(dāng)前在線人數(shù)為" + webSocketSet.size());
}
/**
* 收到客戶端消息后調(diào)用的方法
*
* @param message 客戶端發(fā)送過來的消息
* @param session
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("來自客戶端的消息:" + message);
try {
//接收到的消息再發(fā)給自己
session.getBasicRemote().sendText(message);
}catch(Exception e){
e.printStackTrace();
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("發(fā)生錯誤");
error.printStackTrace();
}
}
第四步,建立一個簡單的客戶端頁面,建立與websocket連接,并收發(fā)信息;
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" >
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
<body>
<p>最簡單的一個demo,自己發(fā)自己接收</p>
<p><input type="text" id="txt" ></input><button id="button" >發(fā)送消息</button></p>
<p id="recvContent">
</p>
<script src="http://www.jq22.com/jquery/jquery-1.10.2.js"></script>
<script th:inline="javascript" >
<!-- ws客戶端 start -->
var socket;
if(typeof(WebSocket) == "undefined") {
console.log("您的瀏覽器不支持WebSocket");
}else{
console.log("您的瀏覽器支持WebSocket");
socket = new WebSocket("ws://localhost:8080/websocket1");
//打開事件
socket.onopen = function() {
console.log("Socket 已打開");
};
//獲得消息事件
socket.onmessage = function(msg) {
console.log("onmessage:" + msg.data);
$("#recvContent").append('<div style="width:300px;text-align:left;"><span >' + msg.data + '</span></div><br/>');
}
//關(guān)閉事件
socket.onclose = function() {
console.log("Socket已關(guān)閉");
};
//發(fā)生了錯誤事件
socket.onerror = function() {
alert("Socket發(fā)生了錯誤");
};
window.onbeforeunload = function(){
socket.close();
return '';
};
}
//按鈕綁定事件
$("#button").click(function(){
//發(fā)送消息
var value=$("#txt").val();
$("#txt").val("");
socket.send(value);
});
</script>
</body>
</html>
最后,測試。

測試結(jié)果圖
總結(jié)
這就是websocket最最簡單的應(yīng)用,代碼少到到不能再少了,如果要做一對一、一對多的聊天也可以在這上面進行擴展。