`spring-websocket` 和 `tomcat-embed-websocket` 都是用于支持 WebSocket 协议的库,但它们有不同的用途和实现方式。
1. **Spring WebSocket (`spring-websocket`)**:
- `spring-websocket` 是 Spring Framework 的一部分,它提供了一种在 Spring 应用程序中处理 WebSocket 连接的方式。
- 它允许您在 Spring 应用程序中轻松地创建 WebSocket 端点,并通过 Spring MVC 控制器或消息代理处理来自客户端的消息。
- Spring WebSocket 提供了高级功能,如消息拦截器、消息转换器、心跳检测等,使得开发 WebSocket 应用程序更加灵活和方便。
- Spring WebSocket 可以与 Spring 的其他模块(如 Spring Security、Spring Boot)无缝集成,提供全面的解决方案。
2. **Tomcat Embed WebSocket (`tomcat-embed-websocket`)**:
- `tomcat-embed-websocket` 是 Apache Tomcat 的一部分,它提供了 Tomcat 内置的 WebSocket 实现。
- 它允许您在 Tomcat 服务器中创建和管理 WebSocket 端点,并直接使用 Tomcat 提供的 API 来处理 WebSocket 连接。
- Tomcat Embed WebSocket 通常用于基于 Tomcat 的应用程序,或者通过嵌入式 Tomcat 启动的 Spring Boot 应用程序。
总的来说,`spring-websocket` 更适合于使用 Spring 框架开发的应用程序,它提供了更丰富的功能和更好的集成性。而 `tomcat-embed-websocket` 则更适合于直接在 Tomcat 服务器中开发 WebSocket 应用程序,或者与 Tomcat 集成的场景。
代码示例:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
@Component
public class WebSocketHandler extends TextWebSocketHandler {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// 在线人数加1
WebSocketUtil.countAtomic.incrementAndGet();
String userId = session.getAttributes().get("userId").toString();
logger.info("用户:" + userId + "已经上线");
WebSocketUtil.clients.put(userId, session);
logger.info("连接打开, 当前连接数:{},当前在线人数:{}", WebSocketUtil.countAtomic.get(), WebSocketUtil.clients.size());
}
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
logger.info("收到客户端的消息:" + message.getPayload());
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
// 在线人数减一
WebSocketUtil.countAtomic.decrementAndGet();
String userId = session.getAttributes().get("userId").toString();
WebSocketUtil.clients.remove(userId);
logger.info("连接关闭, 当前连接数:{},当前在线人数:{}", WebSocketUtil.countAtomic.get(), WebSocketUtil.clients.size());
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
logger.info("服务端发生了错误" + exception.getMessage());
}
}