-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
119 lines (93 loc) · 2.59 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
const { createServer } = require('http')
const path = require('path')
const cors = require('cors')
const express = require('express')
const socketIo = require('socket.io')
const _includes = require('lodash/includes')
const _reverse = require('lodash/reverse')
const { v4: uuidV4 } = require('uuid')
const PORT = process.env.PORT || 5000
const app = express()
const server = createServer(app)
const io = socketIo(server, {
cors: {
origin: '*',
methods: ['GET', 'POST'],
}
})
app.use(cors())
app.use(express.static(path.join(__dirname, 'build')))
app.use(express.static(path.join(__dirname, 'public')))
app.get('/helo', async (req, res) => {
res.json('helö')
})
server.listen(PORT, '0.0.0.0', () => {
console.log('Listening on port %d', PORT)
})
io.on('connection', async (socket) => {
const sendSockets = () => {
const sockets = Array.from(io.sockets.sockets.values())
.map(({ id, username }) => ({ id, username }))
io.emit('sockets', sockets)
}
const sendRooms = () => {
const userIds = Array.from(io.sockets.sockets.values()).map((s) => s.id)
const rooms = Array.from(socket.adapter.rooms)
.map(([id, sockets]) => ({ id, sockets: Array.from(sockets) }))
.filter((r) => !_includes(userIds, r.id))
io.emit('rooms', _reverse(rooms))
}
sendRooms()
sendSockets()
// socket.on('disconnect', () => {})
socket.on('set username', (username, roomId) => {
const oldUsername = socket.username;
socket.username = username
socket.emit('set username', username)
if (roomId) {
io.to(roomId).emit('send message', {
id: uuidV4(),
roomId,
socketId: socket.id,
time: new Date(),
type: 'notification',
message: `"${oldUsername}" is now "${username}"`,
});
}
sendSockets()
})
socket.on('join room', (roomId) => {
socket.join(roomId)
io.to(roomId).emit('send message', {
id: uuidV4(),
roomId,
socketId: socket.id,
time: new Date(),
type: 'notification',
message: `${socket.username} join`,
});
sendRooms()
})
socket.on('leave room', (roomId) => {
socket.leave(roomId)
io.to(roomId).emit('send message', {
id: uuidV4(),
roomId,
socketId: socket.id,
time: new Date(),
type: 'notification',
message: `${socket.username} left`,
});
sendRooms()
})
socket.on('send message', ({ roomId, message }) => {
io.to(roomId).emit('send message', {
id: uuidV4(),
roomId,
socketId: socket.id,
time: new Date(),
type: 'message',
message,
});
})
})