1.引入websocket依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.7.12</version>
</dependency>
2.创建配置类
@Configuration
@EnableWebSocket
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
3.创建websocket类
@Component
@ServerEndpoint("/websocket/{userId}")
@Slf4j
public class WebSocket {
private Session session;
private static Map<String, WebSocket> webSocketMap = new ConcurrentHashMap<>();
private static List<Session> sessionList = new LinkedList<>();
/**
* 客户端发起websocket连接请求成功建立连接时触发
* @param session
* @param userId
* */
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
this.session = session;
this.webSocketMap.put(userId, this);
sessionList.add(session);
log.info("【websocket消息】有新的连接用户{}, 总数:{}",userId, webSocketMap.size());
}
/**
*客户端关闭时websocket连接时触发
*/
@OnClose
public void onClose(@PathParam("userId") String userId) throws IOException {
session.close();
this.webSocketMap.remove(userId);
log.info("【websocket消息】连接断开, 总数:{}", webSocketMap.size());
}
/**
* 客户端向服务端发送消息时触发
* @param session
* @param message
* @throws IOException
* */
@OnMessage
public void onMessage(Session session, String message) throws IOException {
Map<String, List<String>> requestParameterMap = session.getRequestParameterMap();
String userId = requestParameterMap.get("userId").get(0);
log.info("【websocket消息】收到客户端发来的消息:{}", message);
if (message.startsWith("hello")) {
session.getBasicRemote().sendText(userId+"信息收到" + message.replace("hello", ""));
}
sessionList.forEach(s->{
try {
s.getBasicRemote().sendText(message);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
连接地址:
ws://localhost:(springboot程序的端口号)/{userId} (视个人情况而定)