gpt4 book ai didi

java - 从 java WebSocketStompClient 发送 BinaryMessage

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:59:21 41 4
gpt4 key购买 nike

根据 ( 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) 是否支持发送二进制消息?

更新:

以下客户端配置有效:

WebSocketClient transport = new StandardWebSocketClient();
WebSocketStompClient stompClient = new WebSocketStompClient(transport)

最佳答案

我可以通过发送 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);
}

}

关于java - 从 java WebSocketStompClient 发送 BinaryMessage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30489522/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com