Skip to content

Instantly share code, notes, and snippets.

@itsvinayak
Created August 21, 2024 19:05
Show Gist options
  • Save itsvinayak/a524e50feb447b82ecedd9e30ad29c3f to your computer and use it in GitHub Desktop.
Save itsvinayak/a524e50feb447b82ecedd9e30ad29c3f to your computer and use it in GitHub Desktop.
WebSocketServer for push push notifications examples
const port = 3000;
const ws = require("ws");
const server = require("http").createServer();
const connection = [];
const wss = new ws.WebSocketServer({ server });
server.listen(port, () => {
console.log(`Server started on port ${server.address().port}`);
});
wss.on("connection", (ws) => {
console.log("New connection");
connection.push(ws);
ws.send("Welcome to the chat room", ws);
ws.on("message", (message) => {
console.log(`Received message => ${message.toString()}`);
connection.forEach((client) => {
if (client !== ws && client.readyState === ws.OPEN) {
client.send(message.toString());
}
});
});
ws.on("close", () => {
console.log("Connection closed");
});
});
// client code
// let ws = new WebSocket('ws://localhost:3000');
// ws.onmessage = msg => console.log(msg.data);
// ws.send('Hello!');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment