欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

基于springboot @EnableWebSocket 注解完成基本的socket通信以及socket握手权限

程序员文章站 2022-06-29 22:49:12
...

基于spring boot 完成客户端实时通信,此处对整体流程做了简要实现,下一篇讲在此业务上实现通信优化

不涉及socket存储处理以及发送的逻辑代码

首先添加pom 依赖

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-websocket</artifactId>
            </dependency>

然后添加 @EnableWebSocket 注解 设置socket服务注册


@Configuration
@EnableWebSocket
public class WebSocketHandShakeConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {

//注册通信接口
    @Autowired
    private WebSocketController testWebSocketController;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
//注册socket地址,以及允许所有请求  以及拦截器验证权限
        registry.addHandler(testWebSocketController, "/socketserver")
                .addInterceptors(new HandShakeInterceptor()).setAllowedOrigins("*");
    }

}

实现通信接口

@RestController
public class WebSocketController extends TextWebSocketHandler {

   

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("WebSocket服务端连接: "+session.getAttributes().get("token")+"===>");
       
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("WebSocket服务端关闭: 关闭连接状态: "+status);
      
	  //socket关闭处理业务逻辑;
        closeSession(getToken(session));
    }

    @Override
    public void handleMessage(WebSocketSession wsSession, WebSocketMessage<?> message) throws Exception {
        log.info("WebSocket服务端接受:接受来自客户端发送的信息: "+message.getPayload().toString());

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.info("WebSocket服务端异常:连接异常信息: " + exception.getMessage());
        log.info("token : "+getToken(session) + ",deviceId : "+getDeviceId(session) +" => "+ exception.getMessage());
        closeSession(getToken(session));
    }

    private static void closeSession(String token,String deviceId, boolean isError){
        log.info("关闭通信后 处理业务");
    }
	
	
}

权限验证,根据自己具业务验证权限

public class HandShakeInterceptor  extends HttpSessionHandshakeInterceptor {

    private final Logger logger = LoggerFactory.getLogger(HandShakeInterceptor.class);
    /*
     * 在WebSocket连接建立之前的操作,以鉴权为例
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
        String token = serverRequest.getServletRequest().getParameter("token");
        if (("null".equals(token) || TokenCacheUtils.validateToken(token))) {
           //此处将token传递到WebSocketController,必须写否则拿不到数据
            attributes.put("token", token);
            return super.beforeHandshake(request, response, wsHandler, attributes);
        } else {
            return false;
        }
    }



    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                               WebSocketHandler wsHandler, Exception ex) {
        // 省略根据业务处理
    }
}