Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aminkhoshzahmat/5e9ad80c8ccd4100f76c765c4491b7be to your computer and use it in GitHub Desktop.
Save aminkhoshzahmat/5e9ad80c8ccd4100f76c765c4491b7be to your computer and use it in GitHub Desktop.
WebSocket Nodejs Sample
const { log } = require("console");
const http = require("http");
const WebSocketServer = require("websocket").server;
let connections = [];
const httpServer = http.createServer();
const websocket = new WebSocketServer({ httpServer: httpServer });
httpServer.listen(8080, () =>
console.log("My server is listening on port 8080")
);
websocket.on("request", (request) => {
console.log(request);
const connection = request.accept(null, request.origin);
connection.on("message", (message) => {
connections.forEach((c) =>
c.send(`User${connection.socket.remotePort} says ${message.utf8Data}`)
);
});
connections.push(connection);
connections.forEach((c) =>
c.send(`User${connection.socket.remotePort} connected`)
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment