Last active
August 15, 2018 19:51
-
-
Save muhozi/f445cc5fcdcb0d31cbf381f1726db507 to your computer and use it in GitHub Desktop.
Use socket.io in react native
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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