-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
38 lines (27 loc) · 1.02 KB
/
server.js
File metadata and controls
38 lines (27 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const express = require("express");
const ServerSocket = require("ws").Server;
const PORT = 8080;
const server = express().listen(PORT, () =>
console.log(`Server running on port ${PORT}`),
);
const wss = new ServerSocket({ server });
// `ws` is Websocket sent by client (Actually, it's the server-side Websocket instance representing the connection to that client, it's not "real" Websocket client)
// `req` is HTTP request object sent by client
wss.on("connection", (ws, req) => {
console.log("[Client connected]");
console.log("Req", req.headers);
ws.id = req.headers["sec-websocket-key"].substring(0, 8);
ws.send(`[Client ${ws.id} is connected]`);
// Add event listener for message event
ws.on("message", (data) => {
console.log(`[message from client: ${data}]`);
let clients = wss.clients;
console.log(wss.clients);
clients.forEach((client) => {
client.send("[Broadcast] [Get message from server]");
});
});
ws.on("close", () => {
console.log("[Client disconnected]");
});
});