编程文汇

spring boot websocket如何处理二进制消息


#1

在普通websocket教程中,都是描述如何接受字符串,转成对象,这在web环境中是很常见的。同时,在游戏开发中,发送二进制消息,也十分普遍,因为二进制消息普遍更简短,也就意味着更少的序列化时间,更利于在网络上传输。

那么在spring boot 的websocket中,如何处理二进制呢? 有个就是转为这种情况而生,BinaryWebSocketHandler,在这个接口中,处理函数的参数变成了二进制消息,代码如下:

@Configuration
    @EnableAutoConfiguration
    @EnableWebSocket
    public class AppWebSocket {

        public static void main(String[] args) {
            SpringApplication.run(AppWebSocket.class, args);
        }

        @Component
        public static class MyWebSocketConfigurer implements WebSocketConfigurer {

            @Override
            public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
                registry.addHandler(new MyTextHandler(), "/text").withSockJS();
                registry.addHandler(new MyBinaryHandler(), "/binary").withSockJS();
            }
        }

        @Component
        public static class MyTextHandler extends TextWebSocketHandler {
            public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
                session.sendMessage(new TextMessage("hello world"));
            }
        }

        @Component
        public static class MyBinaryHandler extends BinaryWebSocketHandler {
            public void handleBinaryMessage(WebSocketSession session, BinaryMessage message) {
                try {
                    session.sendMessage(new BinaryMessage("hello world".getBytes()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }