我整天都在努力解决这个问题,我无法解决。我正在使用Socket.io for Java,并使用Spring Boot创建了一个非常简单的服务器:
@Component
@RequiredArgsConstructor
public class SocketConnection {
private final SocketIOServer server = new SocketIOServer(getSocketConfiguration());
@PostConstruct
public void startSocketServer() {
server.start();
server.addConnectListener(this::sendAnnouncementToClient);
}
public Configuration getSocketConfiguration() {
Configuration config = new Configuration();
config.setPort(2000);
return config;
}
public void sendAnnouncementToClient(SocketIOClient client) {
client.sendEvent("announcement", "Some text");
}
}
我正在将socket.io-client与React.js用作客户端,我想像这样连接到服务器:
const socket = socketIOClient("https://mydomain.herokuapp.com", {
reconnection: true,
reconnectionAttempts: Infinity,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
randomizationFactor: 0.5,
policyPort: 2000
});
class SocketData extends Component {
state = {
websocketData: [],
isClientConnected: true
}
componentDidMount() {
socket.on("connect", () => {
this.setState({
isClientConnected: true
})
});
socket.on("connect_error", error => {
console.log(error);
console.log("CONNECTION ERROR")
this.setState({
isClientConnected: false
})
})
socket.on("announcement", data => {
console.log(data);
this.setState({
websocketData: data
})
})
}
render() {
if (this.state.isClientConnected) {
if (this.state.websocketData) {
return this.state.websocketData
} else {
return "Waiting...";
}
} else {
return "Not connected!";
}
}
}
在本地运行它可以正常工作。客户端连接到服务器,反之亦然。当我要将整个服务器发送到Heroku平台时,问题就出了(以客户端在本地运行的方式,仅部署服务器)。转到https//localhost:3000/
之后,控制台中会立即显示一条消息:
GET https://mydomain.herokuapp.com/socket.io/?EIO=3&transport=polling&t=NEmqdq8
:
State: 404
Version: HTTP/1.1
Headers: {
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:3000
[...]
基本上,客户端似乎找不到连接的路径,我也不知道为什么。我绝对确定Socket.IO正确打开,如启动Spring Boot时此消息所示:
2020-08-02T19:45:27.999136+00:00 app[web.1]: 2020-08-02 19:45:27.998 INFO 4 --- [ntLoopGroup-2-1] c.c.socketio.SocketIOServer: SocketIO server started at port: 2000
。
请您帮我,我真的很高兴