Skip to content

Instantly share code, notes, and snippets.

@rambabu-patidar
Created January 24, 2026 14:33
Show Gist options
  • Select an option

  • Save rambabu-patidar/c16809d9303499eea93e7e3ff1f3375b to your computer and use it in GitHub Desktop.

Select an option

Save rambabu-patidar/c16809d9303499eea93e7e3ff1f3375b to your computer and use it in GitHub Desktop.
Very very simple example of how you can use websocket for bi-directional communication between client and server.

WebSocket

This code comes from this youtube channel The Complete Guide to WebSockets one of the best channel to learn Networking and Deep dive concepts of System Design etc.

const http = require("http");
const WebSocket = require("websocket").server;

let connection = null;

const httpServer = http.createServer((req, res) => {
	console.log("HTTP Request Received....");
});

// websocket need the http server which it will use and upgrade the TCP connection to ws://
const websocket = new WebSocket({
	httpServer: httpServer,
});

httpServer.listen(8080, () => {
	console.log("Started the HTTP Server");
});

// Upgrade the connection here from TCP to WS
websocket.on("request", (request) => {
	connection = request.accept(null, request.origin);

	connection.on("open", () => console.log("OPENED!!"));
	connection.on("close", () => console.log("CLOSED!!"));
	console.log("Set up the events");
	connection.on("message", (message) => {
		console.log(`Received your message ${message.utf8Data}`);

		connection.send(`Got your message: ${message.utf8Data}`);
	});

	sendEvery5Second();
});

function sendEvery5Second() {
	connection.send("I am server sending you random number: " + Math.random());
	setTimeout(sendEvery5Second, 5000);
}

/*
I haven't implemented the client but you can make the browser as a client 

just go in the console of browser and before that search something on google to not get the 
error about Content-Security-Policy (You should not have empty chrome tab that is wht I am saying)

then create a websocket connection fron client 
then register a event onmessage // with this you can able to get the message from server
then sent the message if client want to send message to server.


ws = new WebSocket("ws://localhost:8080");
ws.onmessage = (message) => console.log("Message Received: " + message.data);
ws.send("Hello server!! I am client, How are you?");
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment