WebSocket with Socket.io
suggest changeInstall socket.io-client
npm i socket.io-client --save
Import module
import SocketIOClient from 'socket.io-client/dist/socket.io.js'
Initialize in your constructor
constructor(props){
super(props);
this.socket = SocketIOClient('http://server:3000');
}
Bind your functions in the constructor as well. This example sends a ping to the server (call _sendPing from a timer such as setInterval; the timer is not shown) and logs the reply.
_sendPing(){
// emit a ding message to the socket server
this.socket.emit('ding');
}
_getReply(data){
//get reply from socket server, log it to console
console.log('Reply from server:' + data);
}
Now, we need to bind these two functions in our constructor:
constructor(props){
super(props);
this.socket = SocketIOClient('http://server:3000');
//bind the functions
this._sendPing = this._sendPing.bind(this);
this._getReply = this._getReply.bind(this);
}
Attach _getReply to the socket so the app can receive the server's dong event. Add this line to the constructor:
this.socket.on('dong', this._getReply);
Whenever the socket server emits dong, the application can receive it.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents