React Native App无法连接到在本地主机上运行的Websocket服务器

时间:2018-10-22 03:15:28

标签: react-native websocket localhost

给出以下代码,用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,它只是为了比较。)

1 个答案:

答案 0 :(得分:0)

那是深夜,我是个假人。 localhost需要网络上运行的服务器的地址。