【发布时间】:2016-02-04 01:00:06
【问题描述】:
我已经解决了这个问题,这段代码帮助我自动检测服务器是 https 还是 http。然后 Javascript 只需创建正确的链接 SockJS 以订阅服务器 Web-socket。
代码如下:
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');
bics.cfapps.io 上的 Spring websocket 运行错误:
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 & ws 但在 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();
}
}
【问题讨论】:
-
请发布您的 websocket 配置和日志。是否从同一来源建立连接?
-
@ThanhNguyenVan 请查看我的更新问题。我的项目在我的本地运行正常,但在 cloudfoundry 上运行错误......如上所述的错误
-
我也遇到了同样的问题,你有什么发现吗
-
阅读这个? docs.run.pivotal.io/release-notes?你需要 wss: 而不是 ws:
标签: cloud-foundry spring-websocket