Websocket在Java中的实践——握手拦截器

2024-06-29 1154阅读

大纲

  • 依赖
  • 握手拦截器
  • 消息处理
  • 测试
  • 参考资料

    在《Websocket在Java中的实践——最小可行案例》一文中,我们看到如何用最简单的方式实现Websocket通信。本文中,我们将介绍如何在握手前后进行干涉,以定制一些特殊需求。

    在《Websocket在Java中的实践——最小可行案例》的基础上,我们希望建立“用户”的概念,即不同用户有自己的用户名。用户只能收到别人发的消息,而不能收到自己的消息。

    这就要求我们服务可以处理ws://localhost:8080/websocket/{uid}这样的请求。而对于uid不存在或者不合法的场景,就要拒绝连接。

    依赖

    在pom.xml中新增

        org.springframework.boot
        spring-boot-starter-websocket
    
    

    握手拦截器

    在绑定接口时,我们可以通过addInterceptors方法给WebSocketHandlerRegistry指定一个握手拦截器。

    package com.nyctlc.withparam.config;
    import java.util.Map;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.http.server.ServerHttpRequest;
    import org.springframework.http.server.ServerHttpResponse;
    import org.springframework.http.server.ServletServerHttpRequest;
    import org.springframework.lang.Nullable;
    import org.springframework.web.socket.WebSocketHandler;
    import org.springframework.web.socket.config.annotation.EnableWebSocket;
    import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
    import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
    import org.springframework.web.socket.server.HandshakeInterceptor;
    import jakarta.servlet.http.HttpSession;
    @Configuration
    @EnableWebSocket
    public class WebSocketConfig implements WebSocketConfigurer {
        @Override
        public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
            registry.addHandler(new com.nyctlc.withparam.handler.WebSocketHandler(), "/websocket/{uid}").setAllowedOrigins("*").addInterceptors(handshakeInterceptor());
        }
    

    这个拦截器需要重载两个方法:beforeHandshake和afterHandshake。它们分别在握手前后被调用。

    我们的需求要求我们在握手之前获取uid。如果uid不存在或者不合法,就会拒绝连接;如果合法,则将其保存到session的属性字段中。

        private HandshakeInterceptor handshakeInterceptor() {
            return new HandshakeInterceptor() {
                @Override
                public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
    			                            WebSocketHandler wsHandler, Map attributes) throws Exception {
                    if (request instanceof ServletServerHttpRequest) {
                        String path = request.getURI().getPath();
                        String prefix = "/websocket/";
                        String uid = path.substring(path.indexOf(prefix) + prefix.length());
                        if (uid.isEmpty()) {
                            return false;
                        }
                        if (uid.contains("/")) {
                            return false;
                        }
                        ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
                        HttpSession session = servletRequest.getServletRequest().getSession();
                        attributes.put("sessionId", session.getId());
                        attributes.put("uid", uid);
                    }
                    return true;
                }
                @Override
                public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
    			                            WebSocketHandler wsHandler, @Nullable Exception exception) {
                }
            };
        }
    }
    

    消息处理

    这次我们在handleTextMessage方法中,判断接收消息的Session的Attributes中的uid是否和Session集合中的一致。这个uid是在上一个步骤中,通过握手拦截器设置的。

    如果一致,说明它们来自同一个用户,则不将该消息发送回自己。

    package com.nyctlc.withparam.handler;
    import java.io.IOException;
    import java.util.HashSet;
    import java.util.Set;
    import org.springframework.web.socket.TextMessage;
    import org.springframework.web.socket.WebSocketSession;
    import org.springframework.web.socket.handler.TextWebSocketHandler;
    public class WebSocketHandler extends TextWebSocketHandler {
        private static final Set sessions = new HashSet();
        @Override
        public void afterConnectionEstablished(WebSocketSession session) throws Exception {
            sessions.add(session);
        }
        @Override
        protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
            for (WebSocketSession webSocketSession : sessions) {
                String uid = session.getAttributes().get("uid").toString();
                if (webSocketSession.isOpen()) {
                    String uidInSession = webSocketSession.getAttributes().get("uid").toString();
                    if (uid.equals(uidInSession)) {
                        continue;
                    }
                    try {
                        webSocketSession.sendMessage(message);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    

    测试

    Websocket在Java中的实践——握手拦截器

    Websocket在Java中的实践——握手拦截器

    参考资料

    • https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/socket/server/HandshakeInterceptor.html
VPS购买请点击我

免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

目录[+]