Skip to content

Instantly share code, notes, and snippets.

@muhozi
Last active August 15, 2018 19:51
Show Gist options
  • Save muhozi/f445cc5fcdcb0d31cbf381f1726db507 to your computer and use it in GitHub Desktop.
Save muhozi/f445cc5fcdcb0d31cbf381f1726db507 to your computer and use it in GitHub Desktop.
Use socket.io in react native
import io from 'socket.io-client/dist/socket.io';
const connectionConfig = {
jsonp: false,
reconnection: true,
reconnectionDelay: 100,
reconnectionAttempts: 100000,
transports: ['websocket']
};
const socket_url = 'http://192.168.56.1:3000';
socket = io(socket_url, connectionConfig);
...
/**
* Listen to a specific channel socket (ex: chat message)
*/
componentDidMount() {
socket.on(
'chat message',
function(msg) {
var messages = this.state.messages;
messages.push(msg);
this.setState({ messages });
}.bind(this)
);
}
/**
* Emit information to a specific channel socket (ex: chat message)
*/
sendMessage = () => {
socket.emit('chat message', this.state.message);
this.setState({ message: '' });
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment