Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io not working with React Native on Android

I'm learning React Native recently, and having trouble with using Socket.IO. I'm using latest React native and cli(just updated), and this is my code:

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View
} from 'react-native';

window.navigator.userAgent = 'react-native';

const io = require('socket.io-client/socket.io');
const socket = io('localhost:3000', { jsonp: false });
socket.connect();

class wschat extends Component { ... }

You can see, the code is quite simple, and no error. This is my server code:

"use strict";
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);

http.listen(3000, () => {
    console.log('WSChat Server for React-Native listening on port 3000');
});

io.on('connection', (socket) => {
    console.log('connected: ' + socket.id);
});

Seems fine, and it is actually worked with ios, but not worked on android. I was enabled remote debugger, and checked the properties, and Socket.IO it self it was loaded well, but no connection was established. You can see the server code, when 'connection' event occured, logged on console.

I used AVD(nexus5) and my device(LG G4 optimus), but both won't worked. What am I missing? Any advice will be very appreciate it!

like image 594
modernator Avatar asked Sep 10 '16 16:09

modernator


1 Answers

The VM react-native runs in isn't nodejs. This means you can't rely on packages such as socket.io-client that in turn rely on nodejs native modules (http, fs, crypto, etc)

I.e. socket.io-client relies on engine-i.o and there you will find stuff like:

var http = require('http');

What's devious is that as long as you're in dev-mode, iOS is backed by nodejs, so it may look like all is working, but if you compile the app, it won't.

Check out react-native-socketio, sadly (as of 2016-09-12) the project isn't well maintained, but it can be made to work.

like image 143
Martin Algesten Avatar answered Nov 03 '22 01:11

Martin Algesten