1 | 1 | var io = require('socket.io')(); |
|
2 | |||
3 | class SocketChat { |
||
4 | constructor(port) { |
||
5 | 1 | this.connections = []; |
|
6 | 1 | this.users = []; |
|
7 | |||
8 | 1 | this.onDisconnect = this.onDisconnect.bind(this); |
|
9 | 1 | this.onLogin = this.onLogin.bind(this); |
|
10 | 1 | this.onConnection = this.onConnection.bind(this); |
|
11 | |||
12 | 1 | io.on('connection', this.onConnection); |
|
13 | |||
14 | 1 | io.listen(port); |
|
15 | 1 | console.log('==> 🌎 Sockets server listens on port %s', port); |
|
16 | } |
||
17 | |||
18 | onChatMsg(data) { |
||
19 | 1 | io.emit('chat msg', data); |
|
20 | } |
||
21 | |||
22 | onNewUser(data) { |
||
23 | io.emit('new user', data); |
||
24 | } |
||
25 | |||
26 | onLogin(data) { |
||
27 | this.users.push({ |
||
28 | user: data.nick, |
||
29 | id: data.socketId |
||
30 | }); |
||
31 | io.emit('update users', JSON.stringify(this.users)); |
||
32 | } |
||
33 | |||
34 | onDisconnect(socket) { |
||
35 | 1 | this.connections.splice(this.connections.indexOf(socket), 1); |
|
36 | 1 | this.users = this.users.filter(user => user.id !== socket.id); |
|
37 | 1 | io.emit('update users', JSON.stringify(this.users)); |
|
38 | 1 | console.log('User disconnected'); |
|
39 | 1 | console.log('Clients connected: ', this.connections.length); |
|
40 | } |
||
41 | |||
42 | onConnection(socket) { |
||
43 | 2 | this.connections.push(socket); |
|
44 | 2 | console.log('Clients connected: ', this.connections.length); |
|
45 | |||
46 | 2 | socket.on('chat msg', this.onChatMsg); |
|
47 | 2 | socket.on('new user', this.onNewUser); |
|
48 | 2 | socket.on('login', this.onLogin); |
|
49 | 2 | socket.on('disconnect', () => { |
|
50 | 1 | this.onDisconnect(socket); |
|
51 | }); |
||
52 | } |
||
53 | } |
||
54 | |||
55 | module.exports = SocketChat; |
||
56 |