Spring boot3简单实现websocket
效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5f6ccd28015dcba769d94e8f2a03fff2.gif#pic_center)
导入WebSocket依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
WebSocketHandler
public class MyWebSocketHandler1 implements WebSocketHandler {
private static final ConcurrentLinkedDeque<WebSocketSession> concurrentLinkedDeque = new ConcurrentLinkedDeque<>();
private String username;
@Override
public void afterConnectionEstablished(WebSocketSession session) {
this.username = (String) session.getAttributes().get("username");
concurrentLinkedDeque.add(session);
System.out.println("用户连接:" + username);
sendMessage(new TextMessage(username + "加入聊天室"));
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) {
sendMessage(message);
}
public void sendMessage(WebSocketMessage<?> message) {
concurrentLinkedDeque.forEach(item -> {
try {
if (item.isOpen()) {
item.sendMessage(message);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
sendMessage(new TextMessage(username + "退出聊天室"));
concurrentLinkedDeque.remove(session);
}
@Override
public boolean supportsPartialMessages() {
return false;
}
}
拦截器
public class MyWebSocketHandshakeInterceptor extends HttpSessionHandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) {
if (request instanceof ServletServerHttpRequest servletRequest) {
String token = servletRequest.getServletRequest().getParameter("token");
String username = servletRequest.getServletRequest().getParameter("username");
if (StringUtils.hasLength(token) && token.equals("321123") && StringUtils.hasLength(username)) {
attributes.put("username", username);
return true;
}
}
return false;
}
}
配置
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(), "/ws/{roomId}").addInterceptors(new MyWebSocketHandshakeInterceptor()).setAllowedOrigins("*");
}
@Bean
public WebSocketHandler myHandler() {
return new MyWebSocketHandler1();
}
@Bean
public ServletServerContainerFactoryBean createWebSocketContainer() {
ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
container.setMaxTextMessageBufferSize(8192);
container.setMaxBinaryMessageBufferSize(8192);
container.setMaxSessionIdleTimeout(3L * 60 * 1000);
container.setAsyncSendTimeout(10L * 1000);
return container;
}
}
Controller
@RestController
public class WebSocketController {
@GetMapping("/send/{msg}")
public HttpStatus sendMessage(@PathVariable String msg) {
MyWebSocketHandler1 myWebSocketHandler1 = new MyWebSocketHandler1();
myWebSocketHandler1.sendMessage(new TextMessage(msg));
return HttpStatus.OK;
}
}