-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathws_server.js
37 lines (36 loc) · 1.07 KB
/
ws_server.js
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
const WebSocket = require('ws')
const nanoid = require('nanoid')
const chalk = require('chalk')
const wss = new WebSocket.Server({ port: 8080, clientTracking: true })
console.log(
chalk.yellowBright('Server on port 8080 is listening (press Ctrl+C to exit)')
)
console.log(chalk.whiteBright('ws://localhost:8080'))
console.log('')
wss.on('connection', ws => {
let id = nanoid(5)
ws.id = id
console.log(
chalk.yellowBright('Client connected. Generate id:'),
chalk.green(id)
)
ws.on('message', data => {
console.log(chalk.yellowBright('Message: '))
console.log(chalk.green(data))
console.log(chalk.yellowBright('from client with id:'), chalk.green(id))
if (data === 'ping') {
ws.send('pong')
return
}
// ws.close() // uncomment this line to test recconection
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN && client.id !== id) {
console.log(
chalk.yellowBright('Send this message to client:'),
chalk.green(client.id)
)
client.send(data)
}
})
})
})