给出以下代码,用wss://echo.websocket.org/
初始化的套接字调用onopen。指向我的本地运行服务器的服务器没有。
constructor(props) {
super(props
// this doesn't work (doesn't call onopen)
this.socket = new WebSocket("ws://localhost:3000/websocket");
// this works (calls onopen)
this.socket = new WebSocket("wss://echo.websocket.org/");
}
componentDidMount() {
console.warn('Mounting..')
this.socket.onopen = () => {
console.warn('onopen');
this.socket.send('Ping')
this.setState({ connected: true }, this.subscribe)
};
this.socket.onerror = (error) => console.log('Error: %o', error);
this.socket.onmessage = (message) => console.warn('Server: ' + message.data);
}
我可以通过wscat
到达并连接到这两种服务
project master % wscat -c wss://echo.websocket.org/
> connected (press CTRL+C to quit)
project master % wscat -c ws://localhost:3000/websocket/
> connected (press CTRL+C to quit)
我在这里想念什么?
(显然,我没有在代码中调用this.socket = new WebSocket()
2x,它只是为了比较。)
答案 0 :(得分:0)
那是深夜,我是个假人。 localhost
需要网络上运行的服务器的地址。