带有 React Native 的 Socket IO

Posted

技术标签:

【中文标题】带有 React Native 的 Socket IO【英文标题】:Socket IO with ReactNative 【发布时间】: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 谁能解释一下为什么?

【问题讨论】:

【参考方案1】:

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

然后使用https://facebook.github.io/react-native/docs/network.html#websocket-support 和https://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);
        );

【讨论】:

以上是关于带有 React Native 的 Socket IO的主要内容,如果未能解决你的问题,请参考以下文章

无法在 Node.JS 和 React-Native (Socket.IO) 之间建立连接

React Native、NodeJS、Socket.io

Socket io客户端在react-native应用程序中不断断开和重新连接

react native 和 java 之间的 Socket.io

React Native socket.io 一直在说

react-native socket.io 来自节点服务器的无尽请求