What are Web Sockets?

      Web sockets is a way to have a interactive session between the user’s browser and the server. With web sockets you will be able to send messages to a server and receive event-based responses without having to poll the server for a response. This enables real time interactivity between multiple users surfing the same website.

Socket.io

      Using socket.io, it makes it really simple to implement a web socket in your app. To use socket.io, you must use it both on the server and client. It is available on npm for the server side and can be linked with a CDN for the client.

Chat example

      We will be going over socket.io’s chat example to see how simple it is to start using web sockets in a basic chat app. We will be looking at 2 files, index.html and index.js. See the code snippets below.

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      var socket = io();
      $('form').submit(function(){
        socket.emit('chat message', $('#m').val());
        $('#m').val('');
        return false;
      });
      socket.on('chat message', function(msg){
        $('#messages').append($('<li>').text(msg));
      });
    </script>
  </body>
</html>

      Looking at index.html on the client side, the socket is established on line 24. On line 25, there is a JQuery event handler that emits the event “chat message” back to the server the value of the text box. On line 30, there is a socket.io event handler that when a “chat message” event is received will append the message as a list item to the unordered list on the DOM.

index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendfile('index.html');
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

      Looking at index.js on the server side, on line 3, a new instance of socket.io is initialized by passing the HTTP server object. On line 9, there is a socket.io event listener then when a connection is established it adds another event listener for “chat messages.” When a “chat message” comes in, it emits the message back out to all client browsers on the server. So, whenever there are multiple users on the website, they will all receive the new messages when they are sent out in real time. With a few lines of code, you can have a responsive web app with real time interactions.