-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat-node.js
37 lines (29 loc) · 942 Bytes
/
chat-node.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 server = require('http').createServer();
const io = require('socket.io')(server);
const port = 3000
const namespace = io.of('/');
let guestCount = 0;
io.on('connection', (socket) => {
console.log(socket.id, 'connected')
socket.on('message', (evt) => {
console.log(evt);
socket.broadcast.emit('message', evt)
})
socket.on('user_joined', (username) => {
// account for guest username
if(!username) {
guestCount++;
username = `guest_${guestCount}`
}
// print connected clients
io.clients((error, clients) => {
if (error) throw error;
console.log(clients); // => [6em3d4TJP8Et9EMNAAAA, G5p55dHhGgUnLUctAAAB]
});
io.emit('user_joined', username)
})
})
io.on('disconnect', (evt) => {
console.log('disconnected')
})
server.listen(port, () => console.log(`server listening on port: ${port}`))