【问题标题】:how to connect two apps with socket.io如何使用 socket.io 连接两个应用程序
【发布时间】:2021-02-10 11:45:07
【问题描述】:

所以我有一个运行良好的 electron-express-socket.io 应用程序。 我现在需要使用 ("socket.io-client") 将 EXPO 应用程序连接到 socket.io。

它们位于不同的端口。

  1. Eelectron-express-socket.io = http://localhost:3000/
  2. EXPO 应用程序 = http://localhost:19006/

我试过这个 https://socket.io/docs/v2/handling-cors/

电子:

const socketio = require('socket.io');
class WebSocket {
  socket = null
  allClients = [];

  socketOptions = {
    'path': '/ws',
    'pingInterval': 10000,
    "handlePreflightRequest": (req, res) => {
      res.writeHead(200, {
        "Access-Control-Allow-Origin": "http://localhost:3000",
        "Access-Control-Allow-Methods": "GET,POST",
        "Access-Control-Allow-Headers": "my-custom-header",
        "Access-Control-Allow-Credentials": false
      });
      res.end();
    }
  }

  constructor(httpServer) {
    //-------------------------------------------------------
    // this.socket = socketio(httpServer, this.socketOptions);
    //-------------------------------------------------------
    this.socket = socketio();
    this.socket.attach(httpServer, this.socketOptions);
    //-------------------------------------------------------

    this.socket.on('connection', (client) => {
      this.onConnection(client);
    });
    this.socket.on('error', this.onClientError);
  }
}

世博APP:

import socketIOClient from "socket.io-client";
const ENDPOINT = "http://localhost:3000/";

export default function App() {
 //-- SocketIO
 const [response, setResponse] = useState("");
 useEffect(() => {
   const socket = socketIOClient(ENDPOINT, {
    withCredentials: false,
  });

   socket.on("currentTime", data => {

     setResponse(data);
   });

 }, []);

//-- SocketIO

  return (
    <View style={styles.container}>
      <Text>{response}Open up App.js to start working on your app!</Text>
      <StatusBar style="auto" />
    </View>
  );
}

我也累了

socketOptions = {
    'path': '/ws',
    'pingInterval': 10000,
    "handlePreflightRequest": (req, res) => {
      res.writeHead(200, {
        "Access-Control-Allow-Origin": "http://localhost:3000",
        "Access-Control-Allow-Methods": "GET,POST",
        "Access-Control-Allow-Headers": "my-custom-header",
        "Access-Control-Allow-Credentials": true
      });
      res.end();
    }
  }

const socket = socketIOClient(ENDPOINT, {
withCredentials: true,
transportOptions: {
  polling: {
    extraHeaders: {
      "my-custom-header": "abcd"
    }
  }
}

});

【问题讨论】:

    标签: socket.io electron expo


    【解决方案1】:

    我所要做的就是将 EXPO 更改为 socket:

    const socket = socketIOClient(ENDPOINT,{
        path: '/ws',
    
       });
    

    【讨论】:

      猜你喜欢
      • 2014-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多