-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
executable file
·50 lines (40 loc) · 1.71 KB
/
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
38
39
40
41
42
43
44
45
46
47
48
49
50
// Create an ExpressJS application object
// and let it servers static files
const express = require('express')
const app = express()
app.use(express.static('public'))
// Create HTTP Server and SocketIO object
const server = require('http').createServer(app)
const io = require('socket.io')(server)
const usernames = {}
// Handle new connection
io.on('connection', (client) => {
// Welcome the new comer
client.emit('welcome')
client.on('username', (username) => {
username = username.trim()
// username must be unique and not empty, ask client to rename invalid name.
if (!username || Object.values(usernames).includes(username)) client.emit('rename')
// save username and serve this user
else {
// update userlist for all clients
usernames[client.id] = username
// Notes:
// `io.emit()` ==> send to every clients
// `client.emit()` ==> send to this client
// `client.broadcast.emit()` ==> send to every clients except this one
// see more at https://socket.io/docs/v4/emit-cheatsheet/
client.broadcast.emit('join', username)
io.emit('usernames', Object.values(usernames))
// Broadcast message from client to all clients
client.on('message', (message) => io.emit('message', { username, message }))
// Handle disconnection and update userlist for all clients
client.on('disconnect', () => {
client.broadcast.emit('left', usernames[client.id])
delete usernames[client.id]
io.emit('usernames', Object.values(usernames))
})
}
})
})
module.exports = { server, io }