LanguagesJavaScriptIntroduction to Web Sockets

Introduction to Web Sockets

A WebSocket API is an advanced technology designed for two-way communication between a web server and a client’s browser. It is an alternative to HTTP communication on the web, allowing you to send messages to the server and receive event-driven responses without having to wait for the server to reply. It provides a persistent, full-duplex two-data communication with a low latency rate.

In layman’s terms, the Web socket establishes a persistent connection between the client and the server and both parties can start transmitting data at any time.

Read: Why I Love WebSockets

Where to use WebSockets

WebSockets are useful for real-time web applications where data on the client-side changes frequently. Some of the examples where WebSockets are used are chat applications, stock market applications, and multi-player games, and so forth.

But why should developers use web sockets if we already have various methods for handling real-time data communication? To understand the reasons behind using WebSockets as an alternative to traditional HTTP communication, we have to first understand what technologies were previously used for handling real-time communication and what the problems associated with them are.

What Are Alternatives to WebSockets?

Below is a list of some of the alternatives to WebSockets when it comes to handling real-time communication in the software development process.

Polling

Polling is a synchronous method in which the client sends a request to the server using an AJAX request to check if there is any data available. The client then receives a response from the server with the required data. It receives the response from the server even if there is no data available. Polling is well-suited for scenarios where developers know the message frequency. However, in most real-time applications, message availability is often unpredictable. Therefore, polling is not an ideal solution for real-time applications.

Large Polling

Large polling is also referred to as Comet. It is a method in which the client opens a connection with the server for a specific period of time. If the server does not have any information at that time, the client keeps opening the connection until there is some data available or until it reaches the designated time limit. The client has to connect to the server constantly in order to receive new data. Comet delays the HTTP response until the server has something to send back to the client, this technique is also called hanging –GET or pending-POST. Because of this, Large-polling – or long polling – is also not a good choice for real-time applications.

Web socket connections provide a solution to cater to the needs of persistent two-way data communication. It provides low latency and persistent connection for the transaction, which can be handled by a server or a client. The next section shows how web sockets work and establish a persistent connection using different events and methods.

Read: Establish Persistent HTTP Connections Using the EventSource

How Do WebSockets Work?

A web socket object provides an API for managing a web socket connection between a client and a server. We show how to create web sockets in the following section.

Create a WebSocket Connection

Open a web socket connection by calling the Web socket constructor, as shown in the following code example:

 
var connection = new WebSocket('ws://localhost:4545, ['soap', 'xmpp']);
 

Notice that the ‘connection’ here is a web socket object. ‘ws’ denotes the URL schema for WebSocket connection. There is also a secure version of web socket connections called ‘wss’, which works the same way https is used for secure HTTP connections.

The second argument in the constructor represents the sub-protocols. This is an optional parameter. These sub-protocols can be a string or an array of strings and they must be one of the registered sub-protocols in the IANA registry.

Read: Getting Started with WebSockets

WebSocket Events

You can attach event handlers while establishing the connection to the server to know when the connection is opened, if there are any errors or if there are incoming messages.

WebSocket Event: open

Once the connection is opened you can send the data to the server using the onOpen callback function, as shown in the following code snippet:

connection.onopen = function () {
  connection.send(‘Connection is opened successfully’); // Send the message to the server
};

message WebSocket Event

The callback for the message event is ‘onmessage’. Websocket message events receive the data from the server.

// Log messages from the server
connection.onmessage = function (e) {
  console.log('Server says: ' + e.data);
};

Error WebSocket Event

In case an error occurs, there is an ‘onerror’ callback for the error event. Here is an example of how to code the error WebSocket event:

// Log errors
connection.onerror = function (error) {
  console.log('Errors: ' + error);
};

Close WebSocket Event

You can close the connection established by the web socket using close. The ‘close’ event has a callback called ‘onclose’ for closing socket connections. Here is an example:

connection.onclose = function(message) {
          console.log(‘Connection closed’, e);
        }; 

Read: Optimizing WebSockets Bandwidth

WebSocket Methods

Below is a list a of WebSocket methods and sample code showing how to use them.

Using the send() WebSocket Method

The send() method is used to transmit data using the connection. It will throw an exception if an error occurs or if the connection no longer exists:

   connection.send('This is a message for server using WebSockets.');

Using the close() WebSocket Method

The close() method is used to terminate an existing connection. The close function needs two arguments – the first one is a code (status code) and the second one is a reason (a text string format) for closure:

  connection.close(500, 'Closing Connection…’);

WebSocket Use Cases

You can use WebSockets where there is a need for low latency and a real-time connection between a server and a client. If your application needs a WebSocket then don’t forget to consider technologies, such as event queues, while building your server-side applications. WebSockets can be used widely in different applications such as:

  • Social media streaming
  • Chat applications
  • Multiplayer online games
  • Updating location data on the fly
  • Stock market applications

Implementing WebSockets in Node.js

ws’ is a popular library for using WebSockets in Node.js applications. To integrate WebSockets in your application, first, you need to install the ‘ws’ library from npm using the following command:

npm init
npm install ws

Now create a server.js file and write into it the following code:

const WebSocket = require('ws')
 
const connection = new WebSocket.Server({ port: 8080 })
 
connection.on('connection', ws => {
  connection.on('message', message => {
    console.log(`Received message => ${message}`)
  })
  connection.send('Message From Server')
})
 

This code creates a new server on port 8080 which is the default port for WebSockets. It adds a call-back function that sends the message ‘Message from server’ to the client and logs the message it receives from the client.

Open the command prompt and run the server using this command:

node server.js

WebSockets n Node.js

In the next step, create a client application by creating a file named client.js and add the following code into it:

 
const WebSocket = require('ws')
const url = 'ws://localhost:8080'
const connection = new WebSocket(url)
 
connection.onopen = () => {
  connection.send('Message From Client') 
}
 
connection.onerror = (error) => {
  console.log(`Errors: ${error}`)
}
 
connection.onmessage = (e) => {
  console.log(e.data)
}
 

Now, run the client-side server using the following command:

 node client.js

You should see following output:

WebSockets tutorials

When you run the client app, you can see a message transmitted by the Server as shown in the above screenshot.

At the same time, a message from the client app is displayed on the server application as shown in the following screenshot:

WebSockets tutorials

Latest Posts

Related Stories