Java实现websocket
导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>1.5.20.RELEASE</version>
</dependency>
编写websocket配置类
1.因为使用@ServerEndpoint实现websocket连接,所以需要进行ServerEndpointExporter配置
2.onStartup进行websocket交互时,发送数据大小限制的配置
@Configuration
public class WebSocketConfig {
/**
* 注入ServerEndpointExporter,
* 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
*/
@Bean
public ServletContextInitializer initializer() {
return new ServletContextInitializer() {
@Override
public void onStartup(ServletContext servletContext) {
// 设置WebSocket文本消息的最大缓冲区大小为25MB
servletContext.setInitParameter("org.apache.tomcat.websocket.textBufferSize", "26214400");
// 如果需要,也可以设置二进制消息的最大缓冲区大小
// servletContext.setInitParameter("org.apache.tomcat.websocket.binaryBufferSize", "52428800");
}
};
}
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
编写websocket服务端
@Component
@ServerEndpoint("/my-websocket")
public class WebSocketServer {
private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);
private static final ConcurrentMap<String, Session> SESSIONS = new ConcurrentHashMap<>();
@OnOpen
public void onOpen(Session session) {
LOGGER.info("New WebSocket connection opened: {}", session.getId());
}
@OnMessage
public void onMessage(Session session, String message) {
LOGGER.info("receive message : {}", message);
SESSIONS.put("xxxx",session);
try {
sedSession.getBasicRemote().sendText(forwardingJson.toString());
} catch (Exception e) { // Catch all exceptions for simplicity, but you should handle specific exceptions separately.
LOGGER.error("Error processing WebSocket message", e);
throw new RuntimeException("Error processing message", e);
}
}
@OnClose
public void onClose(Session session) {
//todo: delete the session
LOGGER.info("WebSocket connection closed: {}", session.getId());
}
@OnError
public void onError(Session session, Throwable throwable) {
LOGGER.error("WebSocket connection error", throwable);
}
private void removeSession(ConcurrentMap<String, Session> map, Session sessionToRemove) {
map.entrySet().removeIf(entry -> Objects.equals(entry.getValue(), sessionToRemove));
}
}
客户端交互:
非加密:ws://localhost:8080/my-websocket
加 密:wss://localhost:8080/my-websocket
推荐测试工具:postman