带有ReactNative的套接字IO

时间:2016-10-25 14:58:54

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

我尝试通过此链接在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 任何人都可以解释为什么?

4 个答案:

答案 0 :(得分:1)

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

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

一起使用

效果很好。

答案 1 :(得分:0)

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


}

答案 2 :(得分:0)

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

答案 3 :(得分:0)

可能会通过错误

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

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

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

然后在 componenDidMount 或 useEffect 函数中添加以下行。切勿在类组件的构造函数下使用它。

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