在其他spring平台中,我使用websocket发送二进制消息,如下所示:
ByteBuffer bf = ByteBuffer.wrap(bytes); old.getBasicRemote().sendBinary(bf);
但是通过spring- boot,我使我的类扩展了TextWebSocketHandler。但是在方法中handleTextMessage(WebSocketSession session, TextMessage message),仅具有参数WebSocketSession,并且没有发送二进制文件的方法。
handleTextMessage(WebSocketSession session, TextMessage message)
我尝试使用BinaryMessage,如下所示:
session.sendMessage(new BinaryMessage(bytes));
但是客户端将结果作为Blob(js type)获得,我不知道该怎么办…
您可以使用 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(); } } } }