我已经解决了这个问题,这段代码帮我自动检测服务器是https还是http。然后Javascript只是创建正确的链接SockJS来订阅服务器Web套接字。
代码如下:
var protocol = location.protocol;
var hostname = location.hostname;
var port = location.port;
var url_prefix = protocol + "//" + hostname + (port === '' ? '' : ':' + port) + contextPath;
var sock = new SockJS(url_prefix + '/connectsocket');
Spring websocket在localhost上运行正常:
var socket = new SockJS('http: //localhost:9091/connect/sockjs');
Spring websocket在bics.cfapps.io上运行错误:
var socket = new SockJS('http: //bics.cfapps.io/connect/sockjs');
错误消息console.log :
WebSocket connection to 'ws://bics.cfapps.io/connect/sockjs/376/7o5_41y7/websocket' failed: Error during WebSocket handshake: Unexpected response code: 400
sockjs-0.3.4.js:807 POST http: //bics.cfapps.io/connect/sockjs/376/colrrwci/xhr_streaming 500 (Internal Server Error)
Whoops! Lost connection to undefined
添加端口4443,但在bics.cfapps.io上仍有错误:
var socket = new SockJS('http: //bics.cfapps.io:4443/connect/sockjs');
错误消息console.log :
XMLHttpRequest cannot load http: //bics.cfapps.io:4443/connect/sockjs/info. No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http: //bics.cfapps.io' is therefore not allowed access. The response had HTTP status code 408.
Whoops! Lost connection to undefined
添加端口4443&但它仍然是bics.cfapps.io上的错误:
var socket = new WebSocket('ws://bics.cfapps.io:4443/connect/sockjs');
错误消息console.log :
WebSocket connection to 'ws://bics.cfapps.io:4443/connect/sockjs' failed: Error during WebSocket handshake: Unexpected response code: 408
Whoops! Lost connection to ws://bics.cfapps.io:4443/connect/sockjs
我的代码配置:
@Configuration
@EnableWebSocket
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/bics");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/connect/sockjs").withSockJS();
}
}
答案 0 :(得分:0)
在评论中指出gregturn给出的答案是正确的:
PWS通过ws:
不支持普通的websockets,但仅通过wss:
支持安全的websockets。此外,它们可以在非标准端口4443上工作。