【问题标题】:Socket IO with ReactNative带有 React Native 的 Socket IO
【发布时间】:2017-03-07 16:49:00
【问题描述】:

我尝试通过点击此链接在 ReactNative 中使用 SocketIO https://github.com/facebook/react-native/issues/4393,
在 IOS 上运行良好,但在 Android 上无法运行 套接字对象的结果 已连接:假

index.android.js

    window.navigator.userAgent = 'react-native';//'react-native';
    const io = require('socket.io-client/socket.io');
    export default class testApp extends Component {
        componentWillMount(){
        this.socket = io.connect('http://localhost:3000', {
                      jsonp: false,
                      transports: ['websocket'] 
        });
        // Socket Object connected:false
    }
    componentDidMount(){
        console.log(this.socket)
        this.socket.on('connect', () => {
           console.log('ready to emit')
           console.log('connected!');
        });
     }

package.json

"react-native": "0.35.0",
"socket.io-client": "^1.5.1"

我找不到类似的问题 我错过了什么?

编辑: 我不确定是否可以使用 ReactNative 在 localhost 中测试 socketIO,但是当我在 IOS 模拟器上测试时它可以工作

已编辑2: 我的错它无法在本地环境服务器上测试 但它适用于 IOS 而不是 android 谁能解释一下为什么?

【问题讨论】:

    标签: socket.io react-native react-native-android


    【解决方案1】:

    我还想将 Socket.IO 与 ExpressJS 服务器和 React Native 一起使用,但无法让它工作。

    然后使用https://facebook.github.io/react-native/docs/network.html#websocket-supporthttps://github.com/websockets/ws

    而且效果很好。

    【讨论】:

    • 如果纯 Websockets 级别太低。我推荐,普里莫斯。非常适合 react-native。
    【解决方案2】:

    clint 中 Socket.io 的这个 FullExample(我希望对你有用)

    import React from 'react';
    
    
    import SocketIOClient from 'socket.io-client'
    const USER_ID = '@userId';
    
    export default class Test extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          messages: [],
          userId: null
        };
    
        this.determineUser = this.determineUser.bind(this);
        this.onReceivedMessage = this.onReceivedMessage.bind(this);
        this.onSend = this.onSend.bind(this);
        this._storeMessages = this._storeMessages.bind(this);
    
        this.socket = SocketIOClient('http://localhost:3000');
        this.socket.on('message', this.onReceivedMessage);
    
        this.determineUser();
      }
    
    
    
      /**
       * When a user joins the chatroom, check if they are an existing user.
       * If they aren't, then ask the server for a userId.
       * Set the userId to the component's state.
       */
      determineUser() {
        AsyncStorage.getItem(USER_ID)
          .then((userId) => {
            // If there isn't a stored userId, then fetch one from the server.
            if (!userId) {
              this.socket.emit('userJoined', null);
              this.socket.on('userJoined', (userId) => {
                AsyncStorage.setItem(USER_ID, userId);
                this.setState({ userId });
              });
            } else {
              this.socket.emit('userJoined', userId);
              this.setState({ userId });
            }
          })
          .catch((e) => alert(e));
      }
    
      // Event listeners
      /**
       * When the server sends a message to this.
       */
      onReceivedMessage(messages) {
        this._storeMessages(messages);
      }
    
      /**
       * When a message is sent, send the message to the server
       * and store it in this component's state.
       */
      onSend(messages=[]) {
        this.socket.emit('message', messages[0]);
        this._storeMessages(messages);
      }
    
      render() {
        var user = { _id: this.state.userId || -1 };
    
        return (
    <></>
        );
      }
    
    
    }
    

    【讨论】:

      【解决方案3】:
      const Local = Platform.OS === 'ios' ? 'http://localhost:3000' : 'http://10.0.2.2:3000'
              import io from "socket.io-client";
      
          //
                 this.socket = io(Local);
                 //  console.log(this.socket)
                  this.socket.emit(Socket_category, Socket_online_subset);
                  this.socket.on(Socket_connection_name, this.onReceivedMessage);
      
      onReceivedMessage =(messages)=> {consol,log(message)}
      

      io.on('connection', function (client) {console.log('User Joined :)')

          client.on(Path_Socket.Socket_category, function (room_name) {
            console.log('joined room online ;) '+room_name);
      
            client.join(room_name);
        })
      

      }

        io.sockets.in(Socket_online_subset)
                  .emit(Socket_connection_name, data(any thing));
      

      【讨论】:

        【解决方案4】:

        可能会出错

        import io from "socket.io-client/socket.io"
        

        然后只需添加以下行......

        import io from "socket.io-client/dist/socket.io";
        

        然后在componentDidMountuseEffect 函数中添加以下行。千万不要在类组件的构造函数下使用。

         var socket = io("https://localhost.com:3000", { jsonp: false });
                // client-side
                socket.on("chat_message", (msg) => {
                    console.log(msg);
                });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-06-23
          • 1970-01-01
          • 2017-07-01
          • 1970-01-01
          • 2016-10-31
          • 1970-01-01
          • 2021-11-22
          相关资源
          最近更新 更多