-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
33 lines (25 loc) · 910 Bytes
/
server.js
File metadata and controls
33 lines (25 loc) · 910 Bytes
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
import { WebSocketServer, WebSocket } from "ws";
const wss = new WebSocketServer({port: 8080})
//
wss.on("connection", (socket, request) => {
const ip = request.socket.remoteAddress
console.log('Connection established')
socket.on('message', (rawData) => {
console.log({raw: rawData})
const data = rawData.toString()
console.log(data)
// this runs for every client connected to the socket
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) { // or client.readyState === 1 (which means open)
client.send(`${ip}: ${data}`)
}
})
})
socket.on('error', (err) => {
console.log(`Error: ${err.message} : ${ip}`)
})
socket.on('close', () => {
console.log('Client Disconnected')
})
});
console.log('Websocket server is live on ws://localhost:8080')