Spring boot3简单实现websocket
效果
文章来源地址https://www.toymoban.com/news/detail-623536.html
导入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) {
//配置handler,拦截器和跨域
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); // 最大闲置时间,3分钟没动自动关闭连接
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;
}
}
文章来源:https://www.toymoban.com/news/detail-623536.html
到了这里,关于Spring boot3简单实现websocket(拦截器,跨域,服务端发送)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!