Spring 中的 WebSockets 是一个相当新的话题,我很想找到更多。
我的问题是连接到来自不同域的服务,我正在与 Lineman 一起构建前端,并在做后端时使用 Spring Boot,我将这些应用程序放在两个不同的端口上:本地主机上的 8000 和 8080。
我遇到了“Access-Control-Allow-Origin” header 的问题,但我已通过在服务器端添加一个过滤器来解决它,该过滤器将允许的来源添加到 header 中。在此之后,我开始在连接时收到以下错误:
GET http://localhost:8080/socket/info 403 (Forbidden)
AbstractXHRObject._start @ sockjs-0.3.4.js:807
(anonymous function) @sockjs-0.3.4.js:841
我的项目中没有 Spring Security,所以这不是授权问题,错误指向 sockJS :that.xhr.send(有效负载); - 从未定义有效负载的地方。我试过但找不到可能开始的调用的根。
我在考虑是否需要在设置连接时向 SockJS 和 Stomp 添加一些附加信息,但在此工具的两个 wiki 页面中都没有太多示例和注释。
您将在下面找到连接 JS 代码。
var socket = new SockJS("http://localhost:8080/socket");
client = Stomp.over(socket);
client.connect({'login': BoatsGame.userName,
'passcode': 'guest'},
function (frame) {
....
The Server Side has a MessageBroker configured :
@Cấu hình
@EnableWebSocketMessageBroker
public class MessageBrokerConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Đậu
public ServletServerContainerFactoryBean createWebSocketContainer() {
ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
container.setMaxTextMessageBufferSize(8192);
container.setMaxBinaryMessageBufferSize(8192);
return container;
}
@Ghi đè
public void configureMessageBroker(MessageBrokerRegistry config) {
//config.enableStompBrokerRelay("/queue", "/topic");
config.enableSimpleBroker("/queue", "/topic","/user");
config.setApplicationDestinationPrefixes("/BoatBattleGame");
}
@Ghi đè
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
stompEndpointRegistry.addEndpoint("/socket").withSockJS();
}
}
我还尝试设置 MessageHandler,因为它可以在配置时设置 OriginAllowe,但我不确定它是如何连接到代理的。
最后想想,这个设置在一个端口上运行时可以正常工作。
Jax 的回答是正确的 :)
registerStompEndpoints 方法让我们有机会设置允许的来源。我们需要在“withSockJs()”选项之前添加它。
@Ghi đè
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
stompEndpointRegistry.addEndpoint("/BO/socket").setAllowedOrigins("*").withSockJS();
}
Tôi là một lập trình viên xuất sắc, rất giỏi!