Created
August 21, 2024 19:05
-
-
Save itsvinayak/a524e50feb447b82ecedd9e30ad29c3f to your computer and use it in GitHub Desktop.
WebSocketServer for push push notifications examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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