如何使用spring boot websocket发送二进制文件? [英] How to send binary with spring boot websocket?
问题描述
在其他spring平台中,我使用websocket发送二进制消息,如下所示:
In other spring platform , I used websocket to send binary message,like this:
ByteBuffer bf = ByteBuffer.wrap(bytes);
old.getBasicRemote().sendBinary(bf);
但是使用spring-boot,我使我的类扩展了TextWebSocketHandler。但是在方法 handleTextMessage(WebSocketSession session,TextMessage message)
中,只有param WebSocketSession并且它没有发送二进制文件的方法。
But with spring-boot, I make my class extends TextWebSocketHandler. But in the method handleTextMessage(WebSocketSession session, TextMessage message)
, only have param WebSocketSession and it has no method to send binary.
我尝试使用BinaryMessage,如下所示:
I try to use BinaryMessage,like this:
session.sendMessage(new BinaryMessage(bytes));
但是客户端得到的结果是Blob(js类型),我不该做什么...
But the client side get the result as Blob(js type), I don't what to do...
推荐答案
您可以使用 BinaryWebSocketHandler 来处理二进制消息通信。
you can use BinaryWebSocketHandler to handle binary message communication.
完整示例
@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();
}
}
}
}
这篇关于如何使用spring boot websocket发送二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!