Spring WebSocket 实现

最近项目中需要使用WebSocket实现实时传递消息功能,网上大多数都是 Socket 实现,而 使用Spring 的WebSocket 的也有不少,但是大多数都只写了一种方法:@ServerEndpoint() 这个方法 ,其实还有另一种方法 WebSocketConfigurer 。这里将会把两种方法介绍下。

@ServerEndpoint() 方法

服务端配置

  • WebSocket 配置类
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}
  • 服务端类
@Component
@ServerEndpoint(value ="/websocket/server1")
public class WebSocketServer {
    private Logger logger = LoggerFactory.getLogger(WebSocketServer.class);
    @OnOpen
    public void onOpen(Session session) {
        logger.info("-----server open");

    }

    @OnMessage
    public void onMessage(Session session, String message) throws IOException {
        logger.info("-----server message:{}", message);
        if ("ABC".equals(message)){
            session.getBasicRemote().sendText("DEF");
        }
    }

    @OnMessage
    public void onBinaryMessage(ByteBuffer buffer, Session session){
        logger.info("-----server binary message:{}", buffer);
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason){
        logger.info("-----server close");
    }

    @OnError
    public void onError(Session session, Throwable throwable){
        logger.error("-----server error", throwable);
    }

}

客户端

public class WebSocketClient extends Endpoint {
    private Logger logger = LoggerFactory.getLogger(WebSocketClient.class);

    @Override
    public void onClose(Session session, CloseReason closeReason) {
        super.onClose(session, closeReason);
        logger.info("-----client close");
    }

    @Override
    public void onError(Session session, Throwable throwable) {
        super.onError(session, throwable);
        logger.error("-----client error", throwable);
    }

    @Override
    public void onOpen(final Session session, EndpointConfig endpointConfig) {
        logger.info("-----client open");
        session.addMessageHandler(new MessageHandler.Whole<String>() {
            public void onMessage(String s) {
                logger.info("-----client message:{}", s);
                try {
                    onHandleMessage(session, s);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        try {
            session.getBasicRemote().sendText("ABC");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void onHandleMessage(Session session, String message) throws IOException {
        if ("DEF".equals(message)){
            session.close();
        }
    }
}

连接方法

        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder
                .create().configurator(new ClientEndpointConfig.Configurator(){
                    @Override
                    public void beforeRequest(Map<String, List<String>> headers) {
                        super.beforeRequest(headers);
                        List<String> values = new ArrayList<String>();
                        values.add("v"); // header value
                        headers.put("k",values);// header
                    }
                }).build();
        Session session = container.connectToServer(WebSocketClient.class, clientEndpointConfig, URI.create("ws://localhost:8181/websocket/server1"));
  • 要想忽略ssl认证,则需要添加SSLContext
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new X509ExtendedTrustManager[]{x509ExtendedTrustManager},new SecureRandom());

        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder
                .create().configurator(new ClientEndpointConfig.Configurator(){
                    @Override
                    public void beforeRequest(Map<String, List<String>> headers) {
                        super.beforeRequest(headers);
                        List<String> values = new ArrayList<String>();
                        values.add("v");
                        headers.put("k",values);
                    }
                }).build();
        clientEndpointConfig.getUserProperties().put(SSL_CONTEXT_PROPERTY, sslContext);

x509ExtendedTrustManager 必须是 javax.net.ssl.X509ExtendedTrustManager 下的包。

连接后Log 信息

2021-10-30 11:17:44.515  INFO 15808 --- [nio-8181-exec-1] c.e.websocket.spring1.WebSocketClient    : -----client open
2021-10-30 11:17:44.518  INFO 15808 --- [nio-8181-exec-2] c.e.websocket.spring1.WebSocketServer    : -----server open
2021-10-30 11:17:44.532  INFO 15808 --- [nio-8181-exec-3] c.e.websocket.spring1.WebSocketServer    : -----server message:ABC
2021-10-30 11:17:44.537  INFO 15808 --- [lient-AsyncIO-1] c.e.websocket.spring1.WebSocketClient    : -----client message:DEF
2021-10-30 11:17:44.538  INFO 15808 --- [lient-AsyncIO-1] c.e.websocket.spring1.WebSocketClient    : -----client close
2021-10-30 11:17:44.538  INFO 15808 --- [nio-8181-exec-4] c.e.websocket.spring1.WebSocketServer    : -----server close

WebSocketConfigurer 方法

服务端配置

  • AbstractWebSocketHandler 实现,主要是接收消息
@Component
public class WebSocketServerHandler extends AbstractWebSocketHandler {
    private Logger logger = LoggerFactory.getLogger(WebSocketServerHandler.class);
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        logger.info("-----server open");
    }
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);

        logger.info("-----server close");
    }
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
        logger.error("-----server error", exception);
    }
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        logger.info("-----server text message:{}", message.getPayload());
        if ("ABC".equals(message.getPayload())){
            session.sendMessage(new TextMessage("DEF"));
        }
    }
    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
        super.handleBinaryMessage(session, message);
        logger.info("-----server binary message:{}", message.getPayload());
    }
    @Override
    protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception {
        super.handlePongMessage(session, message);
        logger.info("-----server pong message:{}", message.getPayload());
    }
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        super.handleMessage(session, message);
        logger.info("-----server message:{}", message.getPayload());
    }
}
  • HandshakeInterceptor 实现,主要作用是对请求的拦截
@Component
public class WebSocketServerInterceptor implements HandshakeInterceptor {
    private Logger logger = LoggerFactory.getLogger(WebSocketServerInterceptor.class);

    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) {
        logger.info("-----server beforeHandshake");
        logger.info("-----server beforeHandshake request Headers :{}",request.getHeaders());
        logger.info("-----server beforeHandshake: attributes{}",attributes);
        return true; // 默认 false ,会报 DeploymentException: The HTTP response from the server [200] did not permit the HTTP upgrade to WebSocket 错误
    }

    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        logger.info("-----server afterHandshake");
    }
}
  • WebSocket 配置,主要是配置跨域、请求路径等
@EnableWebSocket
@Configuration
public class WebSocketServerConfig implements WebSocketConfigurer {
    @Autowired
    private WebSocketServerHandler webSocketServerHandler;
    @Autowired
    private WebSocketServerInterceptor webSocketServerInterceptor;

    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(webSocketServerHandler, "websocket/server2")
                .addInterceptors(webSocketServerInterceptor)
                .setAllowedOrigins("*");
    }
}

客户端

  • AbstractWebSocketHandler实现,主要作用是接收数据,连接监听等。
@Component
public class WebSocketClientHandler extends AbstractWebSocketHandler {
    private Logger logger = LoggerFactory.getLogger(WebSocketClientHandler.class);

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        logger.info("-----client open");
        session.sendMessage(new TextMessage("ABC"));
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);

        logger.info("-----client close");
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
        logger.error("-----client error", exception);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        logger.info("-----client text message:{}", message.getPayload());
        if ("DEF".equals(message.getPayload())){
            session.close();
        }
    }

    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
        super.handleBinaryMessage(session, message);
        logger.info("-----client binary message:{}", message.getPayload());
    }

    @Override
    protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception {
        super.handlePongMessage(session, message);
        logger.info("-----client pong message:{}", message.getPayload());
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        super.handleMessage(session, message);
        logger.info("-----client message:{}", message.getPayload());
        // 所有message 都会运行到这里,一般情况不重写。
    }
}

连接方法

        StandardWebSocketClient standardWebSocketClient = new StandardWebSocketClient();
        WebSocketConnectionManager webSocketConnectionManager = new WebSocketConnectionManager(standardWebSocketClient, webSocketClientHandler, "ws://localhost:8181/websocket/server2");
        webSocketConnectionManager.setOrigin("*");
        HttpHeaders headers = new HttpHeaders();
        headers.set("k", "v");
        webSocketConnectionManager.setHeaders(headers);
        webSocketConnectionManager.start();

连接后Log信息

2021-10-30 11:12:20.997  INFO 15779 --- [nio-8181-exec-1] o.s.w.s.c.WebSocketConnectionManager     : Starting WebSocketConnectionManager
2021-10-30 11:12:20.997  INFO 15779 --- [nio-8181-exec-1] o.s.w.s.c.WebSocketConnectionManager     : Connecting to WebSocket at ws://localhost:8181/websocket/server2
2021-10-30 11:12:26.049  INFO 15779 --- [nio-8181-exec-2] c.e.w.s.WebSocketServerInterceptor       : -----server beforeHandshake
2021-10-30 11:12:26.050  INFO 15779 --- [nio-8181-exec-2] c.e.w.s.WebSocketServerInterceptor       : -----server beforeHandshake request Headers :[sec-websocket-key:"C4QJYOfTt266k/88DfM6Lg==", connection:"upgrade", sec-websocket-version:"13", host:"localhost:8181", k:"v", upgrade:"websocket"]
2021-10-30 11:12:26.052  INFO 15779 --- [nio-8181-exec-2] c.e.w.s.WebSocketServerInterceptor       : -----server beforeHandshake: attributes{}
2021-10-30 11:12:26.067  INFO 15779 --- [nio-8181-exec-2] c.e.w.s.WebSocketServerInterceptor       : -----server afterHandshake
2021-10-30 11:12:26.091  INFO 15779 --- [nio-8181-exec-2] c.e.w.spring2.WebSocketServerHandler     : -----server open
2021-10-30 11:12:26.091  INFO 15779 --- [cTaskExecutor-1] c.e.w.spring2.WebSocketClientHandler     : -----client open
2021-10-30 11:12:26.109  INFO 15779 --- [cTaskExecutor-1] o.s.w.s.c.WebSocketConnectionManager     : Successfully connected
2021-10-30 11:12:26.110  INFO 15779 --- [nio-8181-exec-3] c.e.w.spring2.WebSocketServerHandler     : -----server text message:ABC
2021-10-30 11:12:26.114  INFO 15779 --- [lient-AsyncIO-2] c.e.w.spring2.WebSocketClientHandler     : -----client text message:DEF
2021-10-30 11:12:26.114  INFO 15779 --- [nio-8181-exec-3] c.e.w.spring2.WebSocketServerHandler     : -----server message:ABC
2021-10-30 11:12:26.114  INFO 15779 --- [lient-AsyncIO-2] c.e.w.spring2.WebSocketClientHandler     : -----client close
2021-10-30 11:12:26.114  INFO 15779 --- [lient-AsyncIO-2] c.e.w.spring2.WebSocketClientHandler     : -----client message:DEF
2021-10-30 11:12:26.115  INFO 15779 --- [nio-8181-exec-4] c.e.w.spring2.WebSocketServerHandler     : -----server close

总结

@ServerEndpoint() 这种方式的,操作简单,方法封装的很好,但是不能拦截 WebSocket 的请求,也就不能活去header 值,加入需要校验,那么就会不知所措。

WebSocketConfigurer 这种方法,操作起来稍微复杂一些,但是可以自己设置拦截器,拦截请求,能获取到请求中的所有的内容。

他们都各有利弊,根据自己项目的实际情况来选择使用哪种方式。

最后demo地址:https://github.com/wdmxzf/java-example/tree/webSocket

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,265评论 6 490
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,078评论 2 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 156,852评论 0 347
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,408评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,445评论 5 384
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,772评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,921评论 3 406
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,688评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,130评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,467评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,617评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,276评论 4 329
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,882评论 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,740评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,967评论 1 265
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,315评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,486评论 2 348

推荐阅读更多精彩内容