使用ReactNative的Socket IO

4
我尝试按照这个链接https://github.com/facebook/react-native/issues/4393在ReactNative中使用SocketIO, 在IOS上它工作得非常好,但在Android上却无法工作。 Socket对象的结果是 connected:false。
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中使用本地主机测试socketIO,但当我在IOS模拟器上测试时,它可以工作。

第二次修改: 我的错误是无法在本地环境服务器上进行测试, 但在IOS上可以工作而在Android上不能。 有人可以解释一下为什么吗?

4个回答

2

如果纯Websockets太底层,我建议使用Primus。它与react-native非常兼容。 - mauron85

1

这是一个关于Socket.io在客户端的完整示例(希望对您有用)

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 (
<></>
    );
  }


}

1
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('用户已连接 :)')
    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));

0

可能会出现错误

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);
        });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接