我正在使用Java Spring WebSocket创建一个WebSocket服务器,如果WebSocket客户端是从同一服务器创建的,它实际上可以正常工作。
这是我的服务器端代码,非常简单
// WebSocketConfig.java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Autowired
SocketTextHandler socketTextHandler;
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(socketTextHandler, "/sockets");
}
}
// SocketTextHandler.java
@Component
public class SocketTextHandler extends TextWebSocketHandler {
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message)
throws InterruptedException, IOException {
String payload = message.getPayload();
System.out.println("16: " + session.getId());
session.sendMessage(new TextMessage("Resp: " + payload));
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) {
System.out.println("Server transport error: " + exception.getMessage());
}
}
接下来我将以下WebSocket客户端放入了Spring Boot的静态index.html中:
<html>
<body>
Hello
<script>
console.log('start');
const ws = new WebSocket('ws://localhost:8080/sockets');
ws.onopen = function(evt) {
console.log('onopen', evt);
}
ws.onerror = function(evt) {
console.log('onerror', evt);
}
console.log('done');
</script>
</body>
</html>
然后我访问
http://localhost:8080/index.html
,没有错误,并且我可以看到控制台中的 console.log('onopen', evt)
日志。然而,我的WebSocket客户端应该运行在不同的端口上,即
http://localhost:3000
,我使用相同的index.html,但是当我访问http://localhost:3000/index.html
时,控制台中总是会出现这个错误WebSocket connection to 'ws://localhost:8080/sockets' failed
我想知道WebSockets是否需要从同一服务器连接?还是我漏掉了什么。谢谢!
new WebSocket('ws://localhost:8080/sockets')
中更改端口号。 - tgdaviessetAllowedOrigins("http://localhost:3000", "http://localhost:8080");
或者setAllowedOrigins("*");
来接受任何客户端。 - thusimon