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?");
*/