我在客户端有以下代码:
var sock = new SockJS('http://localhost:8443/quote-socket');
const stompClient = Stomp.over(sock);//connect using your client
stompClient.connect({}, onConnected, onError);
function onConnected() {
stompClient.subscribe('/topic/prices', payload => {
console.log('DATA COMING!');
console.log(payload);
});
stompClient.send("ws/quote/FB",
{},
JSON.stringify({})
);
}
function onError(error) {
console.log('there is an error');
console.log(error);
}
这是Spring引导(即服务器)端:
@Override
@MessageMapping("/quote/{symbol}")
@SendTo("/topic/prices")
public String getSingleQuote(@DestinationVariable("symbol") String symbol, HttpServletResponse response) {
return "Hello";
}
这是Web套接字配置:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/ws");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/quote-socket").setAllowedOrigins("http://localhost:8080").withSockJS();
}
}
我可以在浏览器的控制台中看到以下日志:
Opening Web Socket...
Web Socket Opened...
>>> CONNECT
accept-version:1.0,1.1,1.2
heart-beat:10000,10000
Received data
<<< CONNECTED
heart-beat:0,0
version:1.2
content-length:0
connected to server undefined
>>> SUBSCRIBE
id:sub-0
destination:/topic/prices
>>> SEND
destination:ws/quote/FB
content-length:2
但是未调用controller方法,并且在浏览器端看不到有效负载。这是什么问题?
更新1
我发现它必须像这样使用SockJs
:
var sock = new SockJS('api/quote-socket');
但是在开发过程中,我在另一个端口上运行UI开发服务器(webpack-dev-server),这意味着我需要使用ws
协议,并且由于SockJS不支持,因此我必须使用{ {1}}:
StopJS.client
是否可以在SockJs上使用var url = "ws://localhost:8443/api/quote-socket";
var stompClient = Stomp.client(url);
?在开发过程中我们应该如何使用不同的UI服务器端口,这似乎很常见。