For those like me stumbling across this question looking how to integrate socket.io with react native.
Since React Native has supported websockets for a short time now, you can now set up web sockets really easily with Socket.io. All you have to do is the following
- npm install socket.io-client
- first import react-native
- assign
window.navigator.userAgent = 'react-native';
- import socket.io-client/socket.io
- in your constructor assign
this.socket = io('localhost:3001', {jsonp: false});
So in all it should look like this after npm installing socket.io-client:
import React from 'react-native';
// ... [other imports]
import './UserAgent';
import io from 'socket.io-client/socket.io';
export default class App extends Component {
constructor(props) {
super(props);
this.socket = io('localhost:3001', {jsonp: false});
}
// now you can use sockets with this.socket.io(...)
// or any other functionality within socket.io!
...
}
and then in 'UserAgent.js':
window.navigator.userAgent = 'react-native';
Note: because ES6 module imports are hoisted, we can't make the userAgent assignment in the same file as the react-native and socket.io imports, hence the separate module.
EDIT:
The above solution should work, but in the case it doesn't try create a separate socketConfig.js file. In there import anything that is needed, including const io = require('socket.io-client/socket.io');
and having window.navigator.userAgent = 'react-native';
BEFORE requiring socket.io-client. Then you can connect your socket there and have all listeners in one place. Then actions or functions can be imported into the config file and execute when a listener receives data.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…