WebSocket 握手 - 意外响应代码 200 - AngularJs 和 Spring Boot



当我尝试在 AngularJS 应用程序和 Spring Boot 之间建立 websocket 通信时,出现错误:websocket 握手时出错 - 意外响应代码:200

这是我的JS代码:

function run(stateHandler, translationHandler, $websocket) {
stateHandler.initialize();
translationHandler.initialize();
var ws = $websocket.$new('ws://localhost:8080/socket'); // instance of ngWebsocket, handled by $websocket service
ws.$on('$open', function () {
console.log('Oh my gosh, websocket is really open! Fukken awesome!');  
});
ws.$on('/topic/notification', function (data) {
console.log('The websocket server has sent the following data:');
console.log(data);
ws.$close();
});
ws.$on('$close', function () {
console.log('Noooooooooou, I want to have more fun with ngWebsocket, damn it!');
});
}

这是我的Java代码:

网络套接字配置.java

@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry)
{
stompEndpointRegistry.addEndpoint("/socket")
.setAllowedOrigins("*")
.withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic");
}

WebsocketSecurityConfiguration.java

@Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
messages
// message types other than MESSAGE and SUBSCRIBE
.nullDestMatcher().authenticated()
// matches any destination that starts with /rooms/
.simpDestMatchers("/topic/tracker").hasAuthority(AuthoritiesConstants.ADMIN)
.simpDestMatchers("/topic/**").permitAll()
// (i.e. cannot send messages directly to /topic/, /queue/)
// (i.e. cannot subscribe to /topic/messages/* to get messages sent to
// /topic/messages-user<id>)
.simpTypeMatchers(SimpMessageType.MESSAGE, SimpMessageType.SUBSCRIBE).denyAll()
// catch all
.anyMessage().denyAll();
}

有谁知道如何解决这个问题?
提前谢谢你!

我遇到了类似的问题,我正在使用chrome插件(简单的WebSocket客户端(测试我的websocket连接,并尝试 ws://localhost:8080/handler/连接到我的代码中定义为registry.addEndpoint("/handler").setAllowedOrigins("*").withSockJS();但发生了意外的错误200。我已经通过将/websocket 附加到 chrome 扩展名上的客户端请求字符串来解决此问题,因此您可以尝试在 JS 文件中更改以下行:

var ws = $websocket.$new('ws://localhost:8080/socket');

var ws = $websocket.$new('ws://localhost:8080/socket/websocket');

我不知道为什么这在我的情况下修复了它,我只是偶然发现了它,如果有人 1 可以澄清更多,那就太好了:)

你能试试这个Websocket配置配置吗:

@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry)
{
stompEndpointRegistry.addEndpoint("/socket").setAllowedOrigins("*");      
stompEndpointRegistry.addEndpoint("/socket").setAllowedOrigins("*").withSockJS();
}

所以你同时有websocket和SockJS配置?

如果您将 sockJS 客户端配置为在 websocket 端点上使用 sockJS,则需要使用它。

最新更新