-
Notifications
You must be signed in to change notification settings - Fork 2
/
relay.js
53 lines (45 loc) · 1.35 KB
/
relay.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
var io = require('./lib/socket.io-node/lib/socket.io'),
ChatRoomManager = require('./chat-room-manager');
module.exports = function(server, chatRoomBufferSize, maxBaseNicknameLength, relayOptions) {
var roomManager = ChatRoomManager(chatRoomBufferSize, maxBaseNicknameLength);
var clientIPMap = {};
var getRoom = function(client) {
if (client.connection && client.connection.remoteAddress) {
var ip = client.connection.remoteAddress;
clientIPMap[client.sessionId] = ip;
}
else {
var ip = clientIPMap[client.sessionId];
}
return roomManager.getRoom(ip);
};
var relay = io.listen(server, relayOptions);
relay.on('clientConnect', function(client) {
client.send(client.sessionId);
});
relay.on('clientMessage', function(obj, client) {
switch (obj.action) {
case 'enter':
getRoom(client).addClient(obj.value, client);
break;
case 'nickname':
getRoom(client).changeNickname(obj.value, client);
break;
case 'status':
getRoom(client).broadcastStatus(obj.value, client);
break;
case 'message':
getRoom(client).broadcastMessage(obj.value, client);
break;
}
});
relay.on('clientDisconnect', function(client) {
var room = getRoom(client);
room.removeClient(client);
delete clientIPMap[client.sessionId];
if (room.getClientCount() < 1) {
roomManager.removeRoom(room);
}
});
return relay;
};