You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
npm --global i create-react-appcreate-react-app socket-timernpm 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.