Combine WebSockets with Node.js

WebSocket is an alternative to HTTP communication in web applications. They provide a long-term two-way communication channel between the client and the server.

WebSocket is an alternative to HTTP communication in web applications.

They provide a long-term two-way communication channel between the client and the server.

After the channel is established, the channel will remain open, thereby providing a very fast connection, and the delay time and overhead are low.

Browser support for WebSocket

All modern browsers support WebSocket.

Browser support for WebSockets

How is WebSockets different from HTTP

HTTP is a very different protocol and a different way of communication.

HTTP is a request/response protocol: the server returns some data when the client requests it.

Use WebSockets:

  • ThisThe server can send messages to the clientNothing clearly requested by the customer
  • Client and server canTalk to each other at the same time
  • Little data overheadNeed to exchange to send messages. this meansLow latency communication.

Web socketvery suitablereal timewithLongevitycommunication.

HTTPvery suitableOccasional data exchangeAnd customer-initiated interactions.

HTTP is simplerImplementation, while WebSocket requires more overhead.

Secure WebSockets

Always use a secure encryption protocol for WebSocket,wss://.

ws://Refers to the insecure version of WebSockets (http://WebSockets) and should be avoided for obvious reasons.

Create a new WebSockets connection

const url = 'wss://'
const connection = new WebSocket(url)

connectionIs anWebSocketpurpose.

After the connection is successfully established,openThe event is triggered.

By assigning the callback function toonopenAttribute ofconnectionpurpose:

connection.onopen = () => {

If there are any errors,onerrorThe function callback is triggered:

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

Use WebSockets to send data to the server

After opening the connection, you can send data to the server.

You can conveniently operate insideonopenCallback:

connection.onopen = () => {

Use WebSocket to receive data from the server

Use callback function to monitoronmessage, whenmessageEvent received:

connection.onmessage = e => {

Implement WebSockets server in Node.js

wsIs a popular WebSockets libraryNode.js.

We will use it to build a WebSockets server. It can also be used to implement a client and use WebSocket to communicate between two back-end services.

Easy installation using

yarn init
yarn add ws

There is very little code you need to write:

const WebSocket = require('ws')

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

wss.on(‘connection’, ws => { ws.on(‘message’, message => { console.log(Received message =&gt; </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">message</span><span style="color:#e6db74">}</span><span style="color:#e6db74">) }) ws.send(‘ho!’) })

This code creates a new server on port 8080 (the default port of WebSockets), and adds a callback function when the connection is established, sendingho!Send to the client, and record the message it receives.

View real-time examples on Glitch

This is a real-time example of a WebSockets server:!/flavio-websockets-server-example

This is a WebSockets client that interacts with the server:!/flavio-websockets-client-example

Download mine for freeNode.js manual

More node tutorials: