I heard that Socket.io not worked properly in React Native, so I decided to use plain WebSocket instead.
I'm using node.js for implemeting WebSocket server, and it wasn't hard. With browsers, all of I tried worked, but with React native, none of success.
These are what I tried for implementing websocket server:
- express-ws
- ws
express-ws was just not worked without any error message. Just it saids failed to connect something.
So I changed the module to ws, and this module should be required both client and server, so I did. Server was worked, but when in the app with android on AVD, it saids:
Requiring unknown module "url".If you are sure the module is there, try restarting the packager or running "npm install".
So I removed node_modules directory entirely and reinstall them, but same error shown up again.
I'm using node v6.2.2, and react-native-cli 1.0.0, react-native 0.33.0.
This is the server code with ws module(same as ws module readme):
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ port: 3000 });
wss.on('connection', (socket) => {
socket.on('message', (msg) => {
console.log('Received: ' + msg);
});
socket.send('something');
});
This is client:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
const WebSocket = require('ws');
class wschat extends Component {
constructor() {
super();
}
componentDidMount() {
var socket = new WebSocket("ws://localhost:3000");
socket.on('open', () => {
socket.send('something');
});
socket.on('message', (data, flags) => {
console.log(data);
console.log(flags);
});
}
...
To avoid naming conflict, I was used WebSock instead WebSocket when requiring ws module, but it wasn't problem.
Is there a something that I missed? React Native doc has not much explanations, and it is hard to find working examples. Thanks for reading, and any advice will very appreciate it.