根据(Is it possible to send binary data with STOMP over WebSockets using Spring-WebSockets?),似乎应该可以通过websockets发送带有STOMP的二进制消息。
我已按如下方式配置了WebSocketStompClient:
List<Transport> transports = new ArrayList<>(1);
transports.add(new WebSocketTransport( new StandardWebSocketClient()) );
WebSocketClient transport = new SockJsClient(transports);
WebSocketStompClient stompClient = new WebSocketStompClient(transport);
// using a custom converter to serialize java object to byte[]
stompClient.setMessageConverter( new SerializedJavaObjectMessageConverter() );
我使用以下内容发送消息:
StompHeaders stompHeaders = new StompHeaders();
stompHeaders.setDestination( "/app/greetings");
stompHeaders.setContentType( MimeTypeUtils.APPLICATION_OCTET_STREAM );
session.send(stompHeaders, new Greeting( message ));
我从以下断言中收到一个例外:
Assert.isInstanceOf(TextMessage.class, message, this + " supports text messages only.");
在org.springframework.web.socket.sockjs.client.AbstractClientSockJs(下面)中找到,它似乎只支持TextMessage:
@Override
public final void sendMessage(WebSocketMessage<?> message) throws IOException {
Assert.state(State.OPEN.equals(this.state), this + " is not open, current state=" + this.state);
Assert.isInstanceOf(TextMessage.class, message, this + " supports text messages only.");
String payload = ((TextMessage) message).getPayload();
payload = getMessageCodec().encode(new String[] { payload });
payload = payload.substring(1); // the client-side doesn't need message framing (letter "a")
message = new TextMessage(payload);
if (logger.isTraceEnabled()) {
logger.trace("Sending message " + message + " in " + this);
}
sendInternal((TextMessage) message);
}
上面配置的新的Java客户端WebSocketStompClient(4.2-SNAPSHOT)(即使用SockJS进行回退)是否支持发送二进制消息?
更新
以下客户端配置有效:
WebSocketClient transport = new StandardWebSocketClient();
WebSocketStompClient stompClient = new WebSocketStompClient(transport)
答案 0 :(得分:1)
我能够通过发送TextMessage来实现这一点。我创建了另一个自定义MessageConverter,Base64对序列化对象进行编码/解码:
public class Base64JavaObjectMessageConverter extends AbstractMessageConverter {
public Base64JavaObjectMessageConverter() {
super(MimeTypeUtils.TEXT_PLAIN);
}
@Override
protected boolean supports(Class<?> clazz) {
return true;
}
@Override
public Object convertFromInternal(Message<?> message, Class<?> targetClass) {
byte[] messageBytes = Base64.getDecoder().decode( (byte[])message.getPayload() );
return SerializationUtils.deserialize( messageBytes );
}
@Override
public Object convertToInternal(Object payload, MessageHeaders headers) {
byte[] messageBytes = SerializationUtils.serialize( payload );
return Base64.getEncoder().encode( messageBytes);
}
}