我遇到了完全相同的问题,我用 Web 套接字客户端进行了测试。
为了能够在我的本地环境中手动测试 STOMP,我已经配置了我的 Spring 上下文。这样我就不需要在客户端添加空字符。如果它不存在,它会自动添加。
为此,我在AbstractWebSocketMessageBrokerConfigurer类中添加了:
@Override
public void configureWebSocketTransport(WebSocketTransportRegistration registration) {
registration.addDecoratorFactory(new WebSocketHandlerDecoratorFactory() {
@Override
public WebSocketHandler decorate(WebSocketHandler webSocketHandler) {
return new EmaWebSocketHandlerDecorator(webSocketHandler);
}
});
}
当没有请求正文时,装饰器会自动添加回车(例如:连接命令)。
/**
* Extension of the {@link WebSocketHandlerDecorator websocket handler decorator} that allows to manually test the
* STOMP protocol.
*
* @author Sebastien Gerard
*/
public class EmaWebSocketHandlerDecorator extends WebSocketHandlerDecorator {
private static final Logger logger = LoggerFactory.getLogger(EmaWebSocketHandlerDecorator.class);
public EmaWebSocketHandlerDecorator(WebSocketHandler webSocketHandler) {
super(webSocketHandler);
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
super.handleMessage(session, updateBodyIfNeeded(message));
}
/**
* Updates the content of the specified message. The message is updated only if it is
* a {@link TextMessage text message} and if does not contain the <tt>null</tt> character at the end. If
* carriage returns are missing (when the command does not need a body) there are also added.
*/
private WebSocketMessage<?> updateBodyIfNeeded(WebSocketMessage<?> message) {
if (!(message instanceof TextMessage) || ((TextMessage) message).getPayload().endsWith("\u0000")) {
return message;
}
String payload = ((TextMessage) message).getPayload();
final Optional<StompCommand> stompCommand = getStompCommand(payload);
if (!stompCommand.isPresent()) {
return message;
}
if (!stompCommand.get().isBodyAllowed() && !payload.endsWith("\n\n")) {
if (payload.endsWith("\n")) {
payload += "\n";
} else {
payload += "\n\n";
}
}
payload += "\u0000";
return new TextMessage(payload);
}
/**
* Returns the {@link StompCommand STOMP command} associated to the specified payload.
*/
private Optional<StompCommand> getStompCommand(String payload) {
final int firstCarriageReturn = payload.indexOf('\n');
if (firstCarriageReturn < 0) {
return Optional.empty();
}
try {
return Optional.of(
StompCommand.valueOf(payload.substring(0, firstCarriageReturn))
);
} catch (IllegalArgumentException e) {
logger.trace("Error while parsing STOMP command.", e);
return Optional.empty();
}
}
}
现在我可以执行以下请求:
CONNECT
accept-version:1.2
host:localhost
content-length:0
SEND
destination:/queue/com.X.notification-subscription
content-type:text/plain
reply-to:/temp-queue/notification
hello world :)
希望这可以帮助。
S。