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
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);
});
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.
We can send message to the server using ws.send()
.
We also get a response from the server confirming our message.
Thanks for reading!
Top comments (0)