Combining React with Socket.io - 401-advanced-javascript-v/seattle-javascript-401d29 GitHub Wiki
Setting up the basics
npm --global i create-react-app
create-react-app socket-timer
npm start
Socket.io on the server
npm i --save socket.io
- create a file called server.js in the root folder of the app you generated earlier.
const io = require('socket.io')();
io.on('connection', (client) => {
// here you can start emitting events to the client
});
const port = 8000;
io.listen(port);
console.log('listening on port ', port);
- running node server . You should see a message that it started up successfully: listening on port 8000 .
io.on('connection', (client) => {
client.on('subscribeToTimer', (interval) => {
console.log('client is subscribing to timer with interval ', interval);
});
});
io.on('connection', (client) => {
client.on('subscribeToTimer', (interval) => {
console.log('client is subscribing to timer with interval ', interval);
setInterval(() => {
client.emit('timer', new Date());
}, interval);
});
});
Socket.io on the client
First thing you want to do now is wire up the client socket code that’ll communicate with the server side socket to start a timer, by emitting subscribeToTimer , and consume the timer events emitted by the server.