1,pom文件引入websocket包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2,启动类添加@EnableWebSocket注解,启动支持websocket
3,创建websocket配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
4,创建WebSocket实现@ServerEndpoint(value = "/websocket/{novelId}/{userSessionId}")注解中的路径是前端发送请求的路径,同时 从路径里面获取前端参数
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@ServerEndpoint(value = "/websocket/{novelId}/{userSessionId}")
@Component
@Slf4j
public class WebSocketServer {
private static int onlineCount=0;
private static ConcurrentHashMap<String,ConcurrentHashMap<String,WebSocketServer>> webSocketMap=new ConcurrentHashMap<String,ConcurrentHashMap<String, WebSocketServer>>();
private Session session;
private String novelId="";
private String userSessionId="";
@OnOpen
public void onOpen(Session session, @PathParam("novelId") String novelId ,@PathParam("userSessionId") String userSessionId,EndpointConfig config){
this.session=session;
this.novelId=novelId;
this.userSessionId=userSessionId;
ConcurrentHashMap<String, WebSocketServer> novelMap = webSocketMap.get(novelId);
if (novelMap ==null){
ConcurrentHashMap<String, WebSocketServer> noticeMap= new ConcurrentHashMap<>();
noticeMap.put(userSessionId,this);
webSocketMap.put(novelId,noticeMap);
}else{
WebSocketServer webSocketServer = novelMap.get(userSessionId);
if (webSocketServer==null){
novelMap.put(userSessionId,this);
webSocketMap.put(novelId,novelMap);
}
}
addOnlineCount();
log.info("webSocket连接成功------》当前在线人数:"+getOnlineCount());
}
public static void sendInfo(String message,@PathParam("novelId") String novelId,@PathParam("userSessionId") String userSessionId) {
Iterator<Map.Entry<String, ConcurrentHashMap<String, WebSocketServer>>> iterator = webSocketMap.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<String, ConcurrentHashMap<String, WebSocketServer>> next = iterator.next();
if (next.getKey().equals(novelId)){
ConcurrentHashMap<String, WebSocketServer> value = next.getValue();
Enumeration<String> keys = value.keys();
while (keys.hasMoreElements()){
String s = keys.nextElement();
value.get(s).sendMessage(message);
}
}
}
}
public void sendMessage(String message){
try {
this.session.getBasicRemote().sendText(message);
} catch (IOException e) {
log.error("WebSocket推送消息异常:{}",e);
}
}
@OnClose
public void onClose() {
ConcurrentHashMap<String, WebSocketServer> novelMap = webSocketMap.get(novelId);
if (novelMap ==null){
webSocketMap.remove(novelId);
}else{
novelMap.remove(userSessionId);
webSocketMap.put(novelId,novelMap);
}
subOnlineCount();
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
}
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
附上前端测试代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>websocket测试</title>
<script src="http://cdn.jsdelivr.net/sockjs/1/sockjs.min.js"></script>
<script type="text/javascript">
function WebSocketTest()
{
var ws=null;
if ("WebSocket" in window)
{
console.log("您的浏览器支持 WebSocket!");
// 打开一个 web socket
ws = new WebSocket("ws://127.0.0.1:8080/websocket/test/test");
}
else
{
console.log("浏览器不支持 WebSocket!");
// 浏览器不支持 WebSocket
}
ws.onopen = function()
{
console.log("WebSocket------>已打开");
};
ws.onmessage = function (msg)
{
console.log(msg.data);
console.log("WebSocket------->发现消息");
};
ws.onclose = function()
{
// 关闭 websocket
console.log("连接已关闭...");
};
}
</script>
</head>
<body>
<div id="sse">
<a href="javascript:WebSocketTest()">运行 WebSocket</a>
</div>
</body>
</body>
</html>