Is it possible to send binary data with STOMP over WebSockets using Spring-WebSockets?

半腔热情 提交于 2019-11-29 02:07:10

It seems that org.springframework.web.socket.TextMessage is always used within org.springframework.web.socket.messaging.StompSubProtocolHandler rather than org.springframework.web.socket.BinaryMessage. I've raised a feature request for this SPR-12301 which has been accepted.

message = MessageBuilder.withPayload(message.getPayload()).setHeaders(headers).build();
byte[] bytes = this.stompEncoder.encode((Message<byte[]>) message);

synchronized(session) {
    session.sendMessage(new TextMessage(new String(bytes, UTF8_CHARSET)));
}

Update

  • SPR-12301 was delivered in 4.1.2 but only adds support for receiving binary messages
  • Raised SPR-12475 for sending of binary messages

Try to configure you Server just with ByteArrayMessageConverter:

@Configuration
@EnableWebSocketMessageBroker
public class MyWebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

   @Override
    public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
        messageConverters.add(new ByteArrayMessageConverter());
        return false;
    }

}

UPDATE

Ah! I see that. Thanks:

public TextMessage(byte[] payload) {
    super(new String(payload, UTF_8));
    this.bytes = payload;
}

From other side from STOMP spec:

The body of a STOMP message must be a String. If you want to send and receive JSON objects, ...

According to the ArrayBuffer:

Getting an array buffer from existing data

  • From a Base64 string
  • From a local file

So, I think you don't have a chioce rather than provide you some custom MessageConverter, which converts your byte[] to Base64 String and send it.

On the JavaScript side you should decode that string to the ArrayBuffer somehow.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!