Chapter 5. The Socket.IO Protocol

Socket.io provides a very simple API that is easy to use but exposes a lot of functionality. Moreover, this functionality works uniformly across browsers and the various transport mechanisms provided by socket.io. To achieve this, a socket.io client and server do a lot of work in the background. In this chapter, we will examine and try to understand the communication in socket.io as well as some socket.io internals.

Why do we need another protocol?

The first question to people familiar with WebSocket is, why do we need another protocol when we already have WebSocket? The answer is twofold; socket.io works in a uniform manner across browsers (dating back to Internet Explorer 6), and socket.io provides a much richer API

The WebSocket specification is still under development and is not supported on many of the browsers that are in use. In fact, any version of Internet Explorer prior to IE10 doesn't have support for WebSocket. There are still many people out there using old browsers that don't support WebSocket.

Another problem for WebSocket is firewalls and proxies. Most of the firewalls block any communication (apart from standard HTTP 1.0/1.1), and may not allow a WebSocket connection to be established. The same applies to most proxy servers.

So, if we decide to use just the WebSocket protocol, we have to understand that there will be many people who may not be able to use our application.

Contrary to this, when we build our application using socket.io, the people who can use WebSocket will continue using it, but those who can't will fall back on the next best available transport mechanism and then the next and so on, until they find one that works in the browser, even through the firewalls and proxies, all the way down to iframes (which is rarely used). The default order is as follows:

  • WebSocket
  • FlashSocket
  • XHR long polling
  • XHR multipart streaming
  • XHR polling
  • JSONP polling
  • iframe

It's also worth noting that using JSONP polling, socket.io provides support for cross-domain communication without the need for any special configuration on the server or any special code on the client:

Now, let us take a look at the differences in the API. For this, we will see only the JavaScript client-side API, as any server will have its own implementation and API depending on the programming language used.

The WebSocket API

Let us begin by taking a quick look at a code snippet showing the skeleton of a WebSocket cliet:

<script>
  var socket = new WebSocket('ws://localhost:8080'),

  socket.onopen = function(event) {
    socket.send('Client socket connected'),
  };
  
  socket.onmessage = function(event) {
    console.log('Client received a message', event);
  };
  
  socket.onclose = function(event) {
    console.log('Client socket disconnected', event);
  };
  
  //socket.close()
</script>

The first step, as can be seen in the previous code snippet, is to create a new instance of WebSocket; in this, we have to pass the URI for the WebSocket server. This URI, like any other, has a part that specifies the protocol, which in this case can be either ws (unsecured) or wss (secured); the server address (the server's IP address or valid domain name); and finally, the port.

Ideally, we also need to check if WebSocket is supported on the browser that the user has, but I have skipped that part to focus on the API.

Following the creation of the WebSocket object, we can attach event handlers to it. There are three events exposed by WebSocket, with their corresponding event handlers:

  • open: The onopen event handler
  • message: The onmessage event handler
  • close: The onclose event handler

As is evident by their names, these handlers will be called on the opening of a socket connection, when there is a new message on the socket, and on closing the socket connection, respectively.

For every event, the client receives the event data. In case the event is a message, it contains that message along with other data. The WebSocket client doesn't try to interpret the message or its type, that is to say, it treats all messages as plain text and it is left to the application to interpret and understand it. Also, there is no mention of the namespacing of messages or the multiplexing of socket connections.

If you see the onopen handler, you will notice the send method, which is used by the client to send messages. Again, it can send only plain text, so you have to take care of serialization and deserialization.

Finally, we have the close method, which, as the name suggests, can be used to close the socket connection from the client.

The Socket.IO API

Let us see the same code using sockt.io:

<script>
  var socket = io.connect('http://localhost:8080'),
  
  socket.on('connect', function() {
    socket.send('Client socket connected'),
  });

  socket.on('message', function(data) {
    console.log('Received a message from the server!',data);
  });

  socket.on('disconnect', function() {
    console.log('The client socket disconnected!'),
  });

</script>

The above code snippet looks similar to the one with WebSockets and, not surprisingly, does the same work as the previous code. However, there are some minor changes: instead of using onopen, onmessage, and onclose, we use socket.io's on method to attach the handlers. The advantage is that when we use socket.io's custom events functionality, the API to handle the event remains the same.

As we have already seen, you can emit a new event using the following line of code:

socket.emit("myevent", {"eventData": "..."});

And then receive it using the following:

socket.on("myevent", function(event){...});

As you can see, in this case, we are passing a JSON object for the data; socket.io will take care of serializing and deserializing it for us.

Moreover, socket.io provides support for namespacing of messages, multiplexing of connections, disconnection detection, reconnection, and an API to broadcast messages to all clients.

Considering everything covered in this section, it is not difficult to conclude that socket.io will need its own protocol and mechanism to work.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset