簡體   English   中英

如何通過外部網絡訪問 create-react-app

[英]How can I access create-react-app over external network

我創建了一個簡單的 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>
    );
  }
}

我也在<EchoWebsocket />后面引用了<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()

將 App.js 中的 ip 地址更改為路由器的 ip 地址,並將路由器中的 8765 端口轉發到運行 websocket 回顯服務器的計算機,這樣這段代碼就可以在本地網絡和外部網絡上工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM