如何通过外部网络访问create-react-app

时间:2019-06-29 13:58:15

标签: node.js python-3.x reactjs networking websocket

我创建了一个简单的create-react-app,该应用打开了一个与python中同样简单的websocket回显服务器的websocket连接。

一切都可以在我的本地网络上正常运行,但是我也想尝试从我的本地网络之外进行连接。为此,我已将路由器上的端口3000转发到运行create-react-app应用程序的计算机,并通过通过智能手机上的热点将另一台计算机连接到端口3000上路由器的ip地址进行了测试。

如果未正确连接到python websocket回显服务器,此操作将失败。 我可以从外部网络连接到create-react-app(显示默认徽标,并且页面显示正确),但是问题出在使用react应用连接到python echo服务器时。

从这里出发的任何想法?

这是App.js中的相关代码:

// Address and port of the python websocket server
const URL = 'ws://localhost:8765'

class EchoWebsocket extends Component {
  ws = new WebSocket(URL);

  componentDidMount() {
    // Callback function when connected to websocket server
    this.ws.onopen = () => {
      // on connecting, do nothing but log it to the console
      console.log('Opening new websocket @' + URL);
      console.log('connected')
      console.log('Websocket readyState = ', this.ws.readyState);
    }

    console.log('Websocket readyState = ', this.ws.readyState);

    // Callback function when connection to websocket server is closed
    this.ws.onclose = () => {
      console.log('disconnected')
      console.log('Websocket readyState = ', this.ws.readyState);

      // automatically try to reconnect on connection loss
      console.log('Opening new websocket @' + URL);
    }

    // Callback function to handle websocket error
    this.ws.onerror = event => {
      console.log("WebSocket Error: " , event);
    }
  }

  render() {
    return(
      <div></div>
    );
  }
}

稍后我还将在App.js中引用<EchoWebsocket />

这是python websocket回显服务器:

#!/usr/bin/env python

import asyncio
import websockets

async def echo(websocket, path):
    async for message in websocket:
        await websocket.send(message)

asyncio.get_event_loop().run_until_complete(
    websockets.serve(echo, '', 8765))
asyncio.get_event_loop().run_forever()

1 个答案:

答案 0 :(得分:0)

将App.js中的IP地址更改为路由器的IP地址,并将路由器中的端口8765转发到运行websocket echo服务器的计算机,可以使此代码在本地网络和外部网络上均起作用。 / p>

相关问题