引入依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
创建WebSocketConfig类
package com.redis.studyws.config;
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();
}
}
创建WebSocket类
package com.redis.studyws.config;
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.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
@Component
@Slf4j
@ServerEndpoint("/websocket/{userId}")
public class WebSocket {
private Session session;
private static CopyOnWriteArrayList<WebSocket> webSockets = new CopyOnWriteArrayList<>();
private static Map<String,Session> sessionPool = new HashMap<>();
@OnOpen
public void onOpen(Session session, @PathParam(value = "userId")String userId){
try {
this.session = session;
webSockets.add(this);
sessionPool.put(userId,session);
log.info("WebSocket消息,有新的链接,总数为:"+webSockets.size());
}catch (Exception e){
e.printStackTrace();
}
}
@OnClose
public void onClose(){
try {
webSockets.remove(this);
log.info("WebSocket链接断开,总数为:"+webSockets.size());
}catch (Exception e){
e.printStackTrace();
}
}
@OnMessage
public void onMessage(String message){
log.info("WebSocket收到客户端的消息:"+message);
}
@OnError
public void onError(Session session,Throwable error){
log.error("用户错误:"+session.getId()+"原因:"+error.getMessage());
error.printStackTrace();
}
public void sendAllMessage(String message) {
log.info("【websocket消息】广播消息:"+message);
for(WebSocket webSocket : webSockets) {
try {
if(webSocket.session.isOpen()) {
webSocket.session.getAsyncRemote().sendText(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void sendOneMessage(String userId, String message) {
Session session = sessionPool.get(userId);
if (session != null&&session.isOpen()) {
try {
log.info("【websocket消息】 单点消息:"+message);
session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void sendMoreMessage(String[] userIds, String message) {
for(String userId:userIds) {
Session session = sessionPool.get(userId);
if (session != null&&session.isOpen()) {
try {
log.info("【websocket消息】 单点消息:"+message);
session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}