DEV Community

Darshan Damre
Darshan Damre

Posted on

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!

Top comments (0)