-
Notifications
You must be signed in to change notification settings - Fork 0
/
SocketServer.js
82 lines (70 loc) · 2.12 KB
/
SocketServer.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
'use strict';
import { Server } from 'socket.io';
import { EventEmitter } from 'events';
class SocketServer extends EventEmitter {
constructor (game) {
super();
this.initialize(game);
}
initialize (game) {
const io = (this.io = new Server());
this.game = game;
this.game.setChannel(io);
io.on('connection', function (socket) {
let user;
game.getState(function (users, giver, phase, timeLeft) {
socket.emit('game state', users, giver, timeLeft);
socket.emit(
'taboo message',
'important',
'server',
'Welcome to taboo, please enter your name to join!' +
(timeLeft
? ' A game is currently in progress, feel free to jump right in!'
: '')
);
});
socket.on('enter username', function (username) {
username = username.trim().replace(/\s+/g, ' ');
if (username.length < 3) {
socket.emit('invalid name', 'The name you entered is too short');
} else {
game.addUser(username, socket, function (error, userInfo) {
if (error) {
socket.emit('alternate name', error.message, error.altName);
} else {
user = userInfo;
socket.emit('username accepted', userInfo);
io.emit('new user', userInfo);
}
});
}
});
socket.on('user message', function (message) {
message = message.trim();
if (message.toLowerCase() === '/skip') {
// so hands dont need to leave the keyboard
game.skipCard(user.id);
} else if (message) {
game.processMessage(user.id, message);
}
});
socket.on('skip card', function () {
game.skipCard(user.id);
});
socket.on('disconnect', function () {
if (user) {
game.deleteUser(user, function (err) {
if (!err) {
io.emit('remove user', user.id);
}
});
}
});
});
}
bindToServer (httpServer) {
this.io.attach(httpServer);
}
}
export default SocketServer;