AppDividend
Latest Code Tutorials

WebSockets Tutorial With Example | Getting Started With WebSockets

0

WebSockets Tutorial With Example | Getting Started With WebSockets is today’s topic. Web sockets are defined as two-way communication between the servers and clients, which mean both parties can communicate and exchange data at the same time. WebSockets are the alternative to HTTP communication in the Web Applications. They offer a long-lived, bidirectional communication channel between the client and the server. Once established, the channel is kept open, offering the high-speed connection with low latency and overhead.

Content Overview

WebSockets Tutorial With Example

Web socket protocol is being standardized, and it is becoming a real-time communication between web servers and clients. Web sockets are transforming to cross-platform standard for real-time communication between a client and the server. HTTP protocol has its own set of schemas such as the http and https. Web socket protocol also has a similar kind schema defined in its URL pattern.

Web Socket is the independent TCP-based protocol, but it is designed to support any other protocol as well that would traditionally run only on top of the pure TCP connection.

Web Socket is the transport layer on the top of which any other protocol can run. The Web Socket API supports this ability to define the sub-protocols: protocol libraries that can interpret specific contracts.

Examples of such protocols include XMPP, STOMP, and AMQP. The developers have no longer have to think in terms of an HTTP request-response paradigm.

The only requirement on the browser-side is to run the JavaScript code that can interpret the Web Socket handshake, establish and maintain the Web Socket connection.

On the server side, the industry standard is to use existing protocol libraries that run on top of TCP and leverage a Web Socket Gateway.

A simple example of initial request headers is as follows.

GET ws://websocket.appdividend.com/ HTTP/1.1
Origin: http://appdividend.com
Connection: Upgrade
Host: websocket.appdividend.com
Upgrade: websocket

How WebSockets differ from HTTP

HTTP is a different protocol, and also a different way of communicating. HTTP is the request/response protocol: the server returns some data when the client requests it.

In the WebSocket, the server can send a message to the client without the client explicitly requesting something.

A client and a server can talk to each other simultaneously.

Very little data overhead needs to be exchanged to send messages. This means low latency communication.

Secured WebSockets

Always use the secure, encrypted protocol for WebSockets, wss://.

The ws:// refers to the unsafe WebSockets version (the http:// of WebSockets), and should be avoided for obvious reasons.

Create a new WebSockets connection

We can create a connection using the following code.

const url = 'wss://appdividend.com/post'
const connection = new WebSocket(url)

The connection is a WebSocket object.

When the connection is successfully established, the open event is fired.

Attaching some event handlers immediately to the connection allows you to know when the connection is opened, received incoming messages, or there is an error.

The second argument accepts optional subprotocols. It can be a string or an array of strings. Each string should represent a subprotocol name and server accepts only one of passed subprotocols in the array. Accepted subprotocol can be determined by accessing the protocol property of the WebSocket object.

Listen for it by assigning a callback function to the onopen property of the connection object.

connection.onopen = () => {
  //...
}

If there’s an error, the onerror function callback is fired.

connection.onerror = error => {
  console.log(`WebSocket error: ${error}`)
}

Implement WebSocket on Node.js Server

Let’s take an example and implement the WebSocket on Node.js server.

Create the project folder and inside that folder, create a file called server.js.

Also, open up the terminal and create a package.json file and using the following command.

npm init -y

Then we need to install the ws library for WebSocket.

 

Implement WebSocket on Node.js Server

Then add the following code inside the server.js file.

// server.js

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8080 })

wss.on('connection', ws => {
  ws.on('message', message => {
    console.log(`Received message => ${message}`)
  })
  ws.send('Message From Server!!')
})

So, we have created our server. Now, we need to create a client. So, when the client is connected to the server, we will send and receive the message between client and server.

Now, go to the terminal and start the node server by the following command.

node server

Write the following code inside the client.js file.

// client.js

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(`WebSocket error: ${error}`)
}

connection.onmessage = (e) => {
  console.log(e.data)
}

Here, we have written the code that can connect the server WebSocket, and when the connection is open, we send a message to the server and also, if the server has any message that needs to be received by a client then it will display the message at client-side as well.

Okay, now we need to start a client-side server by the following command.

node client

So, at this time, we have started the two-node server.

  1. client.js
  2. server.js

The output is following for client.js.

 

Create a new WebSockets connection

The output is following for server.js.

 

Secured WebSockets

As soon as we have a connection to the server (when a open event is fired) we can start sending data to the server using the send(‘your message’) method on the connection object.

So, two-way communication is done quickly.

Finally, WebSockets Tutorial With Example | Getting Started With WebSockets is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.