DEV Community

Darshan Damre
Darshan Damre

Posted on

4 3 1

WebSockets for noobs

WebSockets is a bidirectional way of communication between a server and a client.
WebSocket is different from then HTTP. Both protocols are located at layer 7 in the OSI model and depend on TCP at layer 4.WebSocket is designed to work over HTTP ports 443 and 80, thus making it compatible with HTTP. To achieve compatibility, the WebSocket handshake uses the HTTP Upgrade header to change from the HTTP protocol to the WebSocket protocol.

This is how you would create a dead simple web socket server.
I will try to create a web socket server using nodejs.

Install ws using npm.

npm install ws
Enter fullscreen mode Exit fullscreen mode
import { WebSocketServer } from "ws";

const server = new WebSocketServer({ port: 4000 });

server.on("connection", ws => {
  console.log(`new connection`);
  ws.on("message", message => {
    console.log(`Received message ${message}`);
    ws.send(`got your message: ${message}`);
  });
  ws.on("close", () => console.log("closing connection"));

  setInterval(() => {
    ws.send(`Message ${Math.random()}`);
  }, 5000);
});
Enter fullscreen mode Exit fullscreen mode

We can create a web socket client from any browser using the native WebSocket API.

This is how to create a client to connect to our WebSocket server that we opened on port 4000.
Image description

We can send message to the server using ws.send().
We also get a response from the server confirming our message.
Image description

Thanks for reading!

Image of Bright Data

Feed Your Models Real-Time Data – Enhance your AI with up-to-the-minute data.

Utilize our live data feeds for dynamic model training, ensuring your AI systems are always ahead.

Access Real-Time Data

Top comments (0)

Image of Bright Data

Ensure Data Quality Across Sources – Manage and normalize data effortlessly.

Maintain high-quality, consistent data across multiple sources with our efficient data management tools.

Manage Data

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay