配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置WebSocket Bean
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointConfigurator(){
return new ServerEndpointExporter();
}
}
实现webSocket
@Component
@ServerEndpoint("/webSocket/{userId}")
public class WebSocket {
private Session session;
private static int onlineCount = 0;
private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
private String userId;
@OnOpen
public void onOpen(@PathParam("userId") String userId,Session session){
this.userId = userId;
this.session=session;
clients.put(this.userId, this);
addOnlineCount();
System.out.println("【websocket消息】有新的连接,总数:{}"+onlineCount);
}
@OnClose
public void onClose(){
clients.remove(userId);
subOnlineCount();
System.out.println("【websocket消息】连接断开,总数:{}"+onlineCount);
}
@OnMessage
public void onMessage(String message){
for (WebSocket item : clients.values()) {
if (item.userId.equals(userId))
item.session.getAsyncRemote().sendText(message);
}
System.out.println("【websocket消息】收到客户端发来的消息:{}"+message);
}
public static void sendMessageToUserId(String message, String ToUserId){
for (WebSocket item : clients.values()) {
if (item.userId.equals(ToUserId))
item.session.getAsyncRemote().sendText(message);
}
}
public static int findToUserId(String ToUserId){
int count = 0;
for (WebSocket item : clients.values()) {
if (item.userId.equals(ToUserId)){
count++;
}
}
return count;
}
public void sendMessageAll(String message){
for (WebSocket item : clients.values()) {
item.session.getAsyncRemote().sendText(message);
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocket.onlineCount--;
}
public static synchronized Map<String, WebSocket> getClients() {
return clients;
}
}
页面链接WebSocket
if ("WebSocket" in window) {
const ws = new WebSocket("ws://192.168.0.113:8102/rabbit/webSocket/" + userId);
ws.onopen = () => {
console.log("初次连接");
};
ws.onmessage = (res) => {
console.log(res.data);
};
ws.onerror = () => {
console.log("异常");
};
ws.onclose = () => {
console.log("关闭链接");
};
onUnmounted(() => {
console.log("关闭");
ws.close();
});
} else {
console.log("不支持WebSocket");
}