- 37
- 0
- 约5.43千字
- 约 11页
- 2021-01-18 发布于天津
- 举报
springboot 中使用 websocket 简单例子
gradle 中添加依赖,引入 websocket 支持
compile(org.springframework.boot:spring-boot-starter-we bsocket:${springBootVersion})
启用 websocket
package cn.xiaojf.today.ws.configuration;
import
cn.xiaojf.today.ws.handler.CountWebSocketHandler; import
erceptor.HandshakeInterceptor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.Enable
WebSocket;
import
org.springframework.web.socket.config.annotation.WebSo cketConfigurer;
import
org.springframework.web.socket.config.annotation.WebSo cketHandlerRegistry;
import
org.springframework.web.socket.server.standard.ServerE ndpointExporter;
/**
* websocket 配置
* @author xiaojf 2017/3/2 9:50.
*/
@Configuration
@EnableWebSocket
public class WebSocketConfig implements
WebSocketConfigurer {
@Bean
public ServerEndpointExporter
serverEndpointExporter(ApplicationContext context) { return new ServerEndpointExporter();
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new CountWebSocketHandler(), /web/count).addInterceptors(new HandshakeInterceptor());
}
}
消息拦截处理
package erceptor;
import org.springframework. http.server.ServerHttpRequest; import
org.springframework. http.server.ServerHttpResponse; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.server.support.HttpSessi onHandshakeInterceptor;
import java.util.Map;
/**
* 消息拦截处理类
* @author xiaojf 2017/3/2 10:36.
*/
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Maplt;String,
Objectgt; attributes) throws Exception {
// 解决 The extension [x-webkit-deflate-frame] is not supported 问题
if (request.getHeaders().containsKey(Sec-WebSocket-Exte nsions)) {
req
原创力文档

文档评论(0)