对于需要实时的消息通信需要借助socket来进行消息传输
springboot集成websocket
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
@Slf4j
@ServerEndpoint("/websocket/getdata")
@Component
public class WebSocketServer {
//记录在线连接数
private static int onlineCount = 0;
//concurrent包的线程安全set,用来存放每个客户端对应的TelStatusChangeWebSocket对象
public static Map<String, Session> webSocketMap = new ConcurrentHashMap<>();
/**
* 创建连接
* @param session
*/
@OnOpen
public void onOpen(Session session){
//加入set中
webSocketMap.put(session.getId(), session);
//在线数加一
addOnlineCount();
log.info("开启websocket连接");
}
/**
* 关闭websocket连接
* @param session
*/
@OnClose
public void onClose(Session session){
webSocketMap.remove(session.getId());
//在线人数减1
subOnlineCount();
log.info("关闭websocketMap连接");
}
/**
* 当接收到客户端消息后触发
* @param message
* @param session
*/
@OnMessage
public void onMessage(String message, Session session){
log.info("{}传来的消息为{}",session.getId(), message);
}
/**
* 向所有人发送消息
* @param msg
*/
public void sendMessageToAll(String msg){
webSocketMap.forEach((id, session)->{
try {
session.getBasicRemote().sendText(msg);
log.info("消息发送成功{}", msg);
}catch (Exception e){
log.info("{},发送消息失败,原因{}",session.getId(),e);
}
});
}
private void subOnlineCount() {
WebSocketServer.onlineCount--;
}
private void addOnlineCount() {
WebSocketServer.onlineCount++;
}
}
使用WebSocket中出现的问题
- 问题:
javax.servlet.ServletException: javax.websocket.DeploymentException: The path [webSocket] is not valid.
解决@ServerEndpoint("/websocket/getdata")
路径开头要有/
WebSocketConfig
类中注解错误使用成@Configurable
,应该为:@Configuration
。