socket.io in js code example

Example 1: create a web server node js w socket.io

var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

app.get('/', (req, res) => {
  // Ran when a GET request to path '/'
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
  // Ran when a socket connected
});

http.listen(3000, () => {
  // Ran when server is ready to take requestes
});

Example 2: how to check whether the user is online or not using socket.io

const users = {};
io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('login', function(data){
    console.log('a user ' + data.userId + ' connected');
    // saving userId to array with socket ID
    users[socket.id] = data.userId;
  });
  socket.on('disconnect', function(){
    console.log('user ' + users[socket.id] + ' disconnected');
    // remove saved socket from users object
    delete users[socket.id];
  });
});

Tags:

Misc Example