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!
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:
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.
If you want to use socket io for your react native project I would suggest you use feathers js socket io.
https://docs.feathersjs.com/api/socketio.html
This framework also supports Primus, Express, and REST so you got lots of options to choose from. Hope this will help.