Socket IO Study

server.js

var app = require("express")();
var http = require("http").Server(app);
var io = require("socket.io")(http);

app.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.html");
});

var clientCount = 0;

io.on("connection", (socket) => {
  console.log(`A user connected: id = ${socket.id}`);
  io.to(socket.id).emit(
    "message box",
    `Server says: Welcome to the chat room, id ${socket.id}`
  ); // Send to specific guy.

  // List all active user's socket ids.
  // io.sockets.sockets.forEach( client => {
  //   console.log(`Send welcome message to ${client.id}`);
  // });

  io.sockets.emit("client count", ++clientCount); // Send to every one.
  socket.broadcast.emit("message box", `There is a new guy joined! `); // Send to every one but the one himself.

  socket.on("chat message", (msgObj) => {
    io.sockets.emit(
      "message box",
      `(id:${msgObj.id}) ${msgObj.name} says: ${msgObj.message}`
    ); // Send to every one.
  });
  socket.on("disconnect", () => {
    console.log(`User with id = ${socket.id} disconnected.`);
    io.sockets.emit("client count", --clientCount); // Send to every one.
  });
});

http.listen(3000, () => {
  console.log("Server is listening on *:3000");
});

index.html

<body>

<p><b>User: <span id="username"></span></b></p>
<hr />

<div>
    Current total users online: <span id="total-user-count"></span>.
    <hr />
</div>

<form id="form">
    <input id="input" type="text" />
    <input type="submit" value="send"/>
</form>

<div>
    <p><b>Message Box:</b></p>
    <p><hr /></p>
    <div id="msg-box"></div>
    <p><hr /></p>
</div>

<script src="/socket.io/socket.io.js"></script>
<script>

  var urlParams = new URLSearchParams(window.location.search);
  var username = urlParams.get('name');

  var socket = io();

  var form = document.getElementById('form');
  var input = document.getElementById('input');
  var usernameBox = document.getElementById('username');
  var msgBox = document.getElementById('msg-box');
  var userCountBox = document.getElementById('total-user-count');

  if(username){
    usernameBox.textContent = username;
  }
  else{
      console.error('Must set a valid username!');
      document.body.innerHTML = '';
      document.write('Must set a valid username!');
      socket.disconnect();
  }

  socket.on('client count', function(msg) {
    userCountBox.textContent = msg;
  });

  socket.on('message box', function(msg) {
    var item = document.createElement('p');
    item.textContent = msg;
    msgBox.appendChild(item);
  });

  form.addEventListener('submit', function(e) {
    e.preventDefault();
    if (input.value) {
      socket.emit('chat message', {name: username, message: input.value, id: socket.id});
      input.value = '';
    }
  });
</script>

</body>

Good Sources:

https://www.tutorialspoint.com/socket.io/index.htm