【问题标题】:Socket io in React NativeReact Native 中的套接字 io
【发布时间】:2021-05-31 21:26:32
【问题描述】:

我将 Socket.io 用于我的 react-native 项目。 nodejs 服务器由 Heroku 托管。当我尝试从应用程序连接到服务器时,它工作得很好!但是当我尝试发出一条消息时,我在接收 Reactjs 站点上看不到它
这是 react native app 的代码 ->

import { io } from "socket.io-client";

useEffect(() => {
if (tried === true) {
  const socket = io("wss://my-domain-name.herokuapp.com");

  socket.emit("finishPayment", "true");

  setScanned(false);
}
}, [status]);

这是接收客户端代码(React js)->

socket.on("finishPayment", (msg) => {
  console.log(msg);
});

连接已完成(在应用程序中),但未发出消息。
知道为什么会这样吗?
谢谢!

【问题讨论】:

    标签: node.js reactjs react-native socket.io


    【解决方案1】:

    我解决了!!!这是最终代码 ->

    import { Text, View, StyleSheet, Alert } from "react-native";
    
    navigator.__defineGetter__("userAgent", function () {   // you have to import rect native first !!
     return "react-native";
    }); 
    
    import SocketIOClient from "socket.io-client/dist/socket.io.js";
     
      //
    
      useEffect(() => {
    const socket = SocketIOClient("wss://site-name.herokuapp.com/", {
      jsonp: false,
    });
    socket.on("connect", () => {
      console.log("connected");
      socket.emit("hello", "world");
    });
    
    socket.on("connect_error", (err) => {
      console.log(err instanceof Error);
      console.log(err.message); 
    });
    }, []);
    

    【讨论】:

      【解决方案2】:

      这样干净多了。

       const io = require('socket.io-client/dist/socket.io');
      
       const socket = io(
          `API URL`,
          {
            transports: ['websocket'], // you need to explicitly tell it to use websockets
          },
        );
      
        socket.on('connect', () => {
          console.log('connected --------------- socket ---------------');
        });
      
        socket.on('connect_error', err => {
          console.log(err.message);
        });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-03
        • 1970-01-01
        • 1970-01-01
        • 2017-10-10
        相关资源
        最近更新 更多