Socket.io does not work with React Native on Android

I am learning React Native recently and have problems using Socket.IO. I am using the latest version of 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 pretty simple and there is 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 to be beautiful, and it actually works with ios, but does not work on android. I turned on the remote debugger and checked the properties, and Socket.IO itself it was loaded well, but the connection was not established. You can see the server code when the "connection" event occurred, registered on the console.

I used AVD (nexus5) and my device (LG G4 optimus), but both will not work. What am I missing? Any advice would be greatly appreciated for that!

+5
source share
2 answers

VM-native communication is not hosted. This means that you cannot rely on packages like socket.io-client , which in turn rely on native nodejs modules ( http , fs , crypto , etc.)

those. socket.io-client relies on engine-io and there you will find things like:

 var http = require('http'); 

What is the trick that while you are in dev-mode, iOS is supported by nodejs, so it might seem that everything works, but if you compile the application, it won’t.

Check out react-native-socketio , unfortunately (as of 2016-09-12) the project is not supported, but may be in order to work.

+3
source

If you want to use the io socket to respond to your own project, I would suggest you use js socket io feathers.

https://docs.feathersjs.com/api/socketio.html

This structure also supports Primus, Express, and REST, so you have many options to choose from. Hope this helps.

0
source

All Articles