-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
622 lines (561 loc) · 16.5 KB
/
index.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//TCP Server
var maps = require('hashmap')
var net = require('net');
var HOST = 'localhost';
var PORT = 9399;
var SERVER_IN = "<= "
var USER_IN = "=> "
var server = net.createServer();
var sockets = []; // Store user sockets
var userNames = []; // store user names
var userStates = []; // 0 -> new user 1-> User added with name 2-> User in a chat room 3-> User in room, in private chat
var userChatRoom = new maps.HashMap(); // user to chatRoom mapping
var chatRoomsMap = new maps.HashMap(); // chatRoom to users mapping
var privateChatDialogue = new maps.HashMap(); // HashMap to store private chat between two users
//Adding some chat rooms
chatRoomsMap.set("chat",null);
chatRoomsMap.set("hottub",null);
chatRoomsMap.set("minastirith",null);
chatRoomsMap.set("theHikingGroup",null);
chatRoomsMap.set("huntingForJob",null);
server.listen(PORT, HOST);
// TCP server connection
server.on('connection', function(socket) {
sockets.push(socket);
userStates[sockets.indexOf(socket)] = 0 ; // Initial user state is 0 -> new user
console.log('CONNECTED: ' + socket.remoteAddress +':'+ socket.remotePort);
socket.write(SERVER_IN + "Welcome to Chat-O \n");
socket.write(SERVER_IN + "Login Name?\n"+USER_IN);
socket.on('data', function(data) {
receiveData(socket, data);
});
socket.on('end', function() {
console.log("---- in server");
closeSocket(socket);
});
}).listen(PORT, HOST);
// Close the socket
function closeSocket(socket) {
try
{
var i = sockets.indexOf(socket);
if (i != -1) {
if(userStates[i] == 3)
{
console.log("---- in close socket for user in private chat ");
leavePrivateChat(socket);
leaveRoom(socket);
userNames.splice(i,1);
}
else if(userStates[i] == 2) // If user was in a room , clear all states
{
console.log("---- in close socket for user in chat room");
leaveRoom(socket);
userNames.splice(i,1);
}
else if(userStates[i] == 1) // if user was registered with name
{
userNames.splice(i,1);
}
userStates.splice(i,1); // remove user state
sockets.splice(i, 1);
}
}
catch(e)
{
console.log("Exception in close socket");
console.log(e);
}
}
// Leave Private Chat
function leavePrivateChat(socket) {
try
{
var i = sockets.indexOf(socket);
if (i != -1) {
if(privateChatDialogue.has(userNames[i]))
{
var another = privateChatDialogue.get(userNames[i]);
privateChatDialogue.remove(userNames[i]);
userStates[i] = 2;
if(privateChatDialogue.has(another))
{
privateChatDialogue.remove(userNames[i]);
}
userStates[userNames.indexOf(another)] = 2;
sockets[i].write(USER_IN);
sockets[userNames.indexOf(another)].write("\n" + SERVER_IN + " * private chat ended.\n" + USER_IN );
}
}
}
catch(e)
{
console.log("Exception in leave private chat");
console.log(e);
}
}
// Leave Room
function leaveRoom(socket) {
try
{
var i = sockets.indexOf(socket);
if (i != -1) {
if(userStates[i] == 2) // If user was in a room
{
console.log("---- in leaveRoom");
var removeUserFromRoom = userChatRoom.get(userNames[i]);
var usersInRoom = chatRoomsMap.get(removeUserFromRoom);
if(usersInRoom.indexOf(userNames[i]) != -1)
{
usersInRoom.splice(usersInRoom.indexOf(userNames[i]) , 1);
}
usersInRoom.forEach(function(user)
{
console.log(user);
sockets[userNames.indexOf(user)].write("\n" + SERVER_IN + " * user has left chat : " + userNames[i] + "\n" + USER_IN );
});
chatRoomsMap.set(removeUserFromRoom , usersInRoom );
userChatRoom.remove(userNames[i]);
userStates[i] = 1;
}
else
{
sockets[i].write(SERVER_IN + "Invalid command! \n" + USER_IN );
}
}
}
catch(e)
{
console.log("Exception in leave room");
console.log(e);
}
}
function timeOutCallBack(socket)
{
try
{
var i = sockets.indexOf(socket);
if(i != -1)
{
console.log("--Timed OUT--");
sockets[i].write(SERVER_IN + "Your private chat request has been ignored\n" + USER_IN);
sockets[i].setTimeout(0);
userStates[i] = 2;
privateChatDialogue.remove(userNames[i]);
}
}
catch(e)
{
console.log(e);
console.log("Time Out callback ");
}
}
// Function called when some data is recived on a socket
function receiveData(socket, data)
{
tempData = cleanInput(data).split(" ");
if(tempData[0] === "/quit") {
socket.end('Goodbye!\n');
}
else if(tempData[0] === "/leave") // Command /leave
{
try
{
var i = sockets.indexOf(socket);
if(i != -1)
{
if(userStates[i] == 3)
{
leavePrivateChat(sockets[i]);
}
else
{
leaveRoom(sockets[i]);
sockets[i].write(SERVER_IN + " ** You are out of the chat room. \n " + USER_IN);
}
}
}
catch(e)
{
console.log("/leave Exception");
console.log(e);
}
}
else if(tempData[0] === "/rooms") // Command /rooms
{
try
{
var i = sockets.indexOf(socket);
if(i != -1)
{
sockets[i].write(SERVER_IN + "Active chat rooms are:\n" );
// Show available chat rooms
chatRoomsMap.forEach(function(value, key) {
var numInGroup = 0;
if(value!= null)
numInGroup = value.length;
sockets[i].write(SERVER_IN + "*"+key+ " (" + numInGroup +")\n");
});
}
sockets[i].write(SERVER_IN + "end of list.\n"+ USER_IN );
}
catch(e)
{
console.log("/rooms Exception");
console.log(e);
}
}
else if(tempData[0] === "/private") // Command /private
{
try
{
var i = sockets.indexOf(socket);
if(i != -1)
{
if(userStates[i] == 2)
{
if(tempData.length == 1)
{
sockets[i].write(SERVER_IN + "Invalid Usage\n"+ USER_IN );
}
else
{
if(!privateChatDialogue.has(userNames[i]))
{
var privateChatWith = tempData[1];
sockets[i].write("\n" + SERVER_IN +" Requesting " + privateChatWith + "... \n" + USER_IN);
sockets[i].setTimeout(20000);
sockets[i].on('timeout', function(data){
timeOutCallBack(sockets[i]);
});
userStates[i] = 3;
privateChatDialogue.set(userNames[i] , privateChatWith);
sockets[userNames.indexOf(privateChatWith)].write("\n"+SERVER_IN + userNames[i] + " is requesting a private chat\n" + USER_IN);
}
else
{
sockets[i].write(SERVER_IN + "You are already in a private chat request. Have patience !!\n"+ USER_IN );
}
}
}
}
}
catch(e)
{
console.log("/private exception");
console.log(e);
}
}
else if(tempData[0] === "/accept") // Command /accept
{
try
{
var i = sockets.indexOf(socket);
if(i != -1)
{
if(userStates[i] == 2)
{
if(tempData.length == 1)
{
sockets[i].write(SERVER_IN + "Invalid Usage\n"+ USER_IN );
}
else
{
var privateChatWith = tempData[1];
if(userStates[userNames.indexOf(privateChatWith)] == 3)
{
userStates[i] = 3;
sockets[i].write("\n" + SERVER_IN + "Accepting...\n" + USER_IN);
sockets[userNames.indexOf(privateChatWith)].setTimeout(0);
privateChatDialogue.set(userNames[i] , privateChatWith);
sockets[userNames.indexOf(privateChatWith)].write("\n"+SERVER_IN + userNames[i] + " accepted your private chat request\n" + USER_IN);
}
else
{
sockets[i].write("\n" + SERVER_IN +" Invalid Usage\n" + USER_IN );
}
}
}
}
}
catch(e)
{
console.log("/accept exception");
console.log(e);
}
}
else if(tempData[0] === "/join") // Command /join
{
try
{
var toJoin = tempData[1];
var i = sockets.indexOf(socket);
if(i != -1)
{
if(userStates[i] == 1) // Join a chat room only if user is registered with a name
{
if(!chatRoomsMap.has(toJoin))
{
sockets[i].write(SERVER_IN + "Invalid chat room!" + "\n" + USER_IN);
}
else
{
userStates[i] = 2;
userChatRoom.set(userNames[i],toJoin);
sockets[i].write(SERVER_IN + "Entering room :" + toJoin + "\n");
var usersInRoom = chatRoomsMap.get(toJoin);
if(usersInRoom)
{
usersInRoom.push(userNames[i]);
chatRoomsMap.set(toJoin , usersInRoom);
usersInRoom.forEach(function(user)
{
if(user === userNames[i])
sockets[i].write(SERVER_IN + "*" + user + " (** This is you)\n");
else
{
sockets[i].write(SERVER_IN + "*" + user + "\n");
sockets[userNames.indexOf(user)].write("\n" + SERVER_IN + " * new user joined room: " + userNames[i] + "\n" + USER_IN );
}
});
}
else
{
usersInRoom = [];
usersInRoom.push(userNames[i]);
chatRoomsMap.set(toJoin , usersInRoom);
sockets[i].write(SERVER_IN + "*" + userNames[i] + " (** this is you)\n");
}
sockets[i].write(SERVER_IN + "end of list.\n" + USER_IN );
}
}
else
{
sockets[i].write(SERVER_IN + "You need to be out of this room to connect to another chat room\n"+USER_IN)
}
}
}
catch(e)
{
console.log("/join exception");
console.log(e);
}
}
else if(tempData[0] === "/addroom") // Command /addroom
{
try
{
if(tempData.length == 1)
{
sockets[i].write(SERVER_IN + "Invalid Usage\n"+ USER_IN );
}
else
{
if(!chatRoomsMap.has(tempData[1]))
{
chatRoomsMap.set(tempData[1],null);
}
}
}
catch(e)
{
console.log("/addroom exception");
console.log(e);
}
}
else // Receive all other data
{
try
{
var i = sockets.indexOf(socket);
if (i != -1)
{
if(tempData[0][0] == '/')
{
sockets[i].write(SERVER_IN + "Unrecognized command! \n" + USER_IN);
return;
}
if(userStates[i] == 3) // In a private chat, send message to only private people
{
console.log("privateChatDialogue");
var sendTo = privateChatDialogue.get(userNames[i]);
if(userStates[userNames.indexOf(sendTo)] == 3)
{
if(tempData && tempData[0].length != 0)
{
sockets[i].write("\n" + SERVER_IN + userNames[i]+ ":" + tempData.join(" ") + "\n" + USER_IN);
sockets[userNames.indexOf(sendTo)].write("\n" + SERVER_IN + userNames[i] +" : " + tempData.join(" ") + "\n" + USER_IN);
}
else
{
sockets[i].write(USER_IN);
}
}
else
{
sockets[i].write(SERVER_IN + " PLEASE WAIT...!!");
}
}
else if(userStates[i] == 2) // In a chat room, send message to everyone in chat room
{
console.log("message in a chat room");
if(tempData && tempData[0].length != 0)
{
inMyRoom = chatRoomsMap.get(userChatRoom.get(userNames[i]));
console.log(i + " " + userNames[i] + " " + userChatRoom.get(userNames[i]));
inMyRoom.forEach(function(user)
{
if(user != userNames[i])
{
if(userStates[userNames.indexOf(user)] == 2 )
sockets[userNames.indexOf(user)].write("\n" + SERVER_IN + userNames[i] +" : " + tempData.join(" ") + "\n" + USER_IN);
}
else
{
if(userStates[userNames.indexOf(user)] == 2 )
sockets[userNames.indexOf(user)].write(SERVER_IN + userNames[i] +" : " + tempData.join(" ") + "\n" + USER_IN);
}
});
}
else
{
sockets[i].write(USER_IN);
}
}
else
{
if(tempData && tempData[0].length != 0)
{
if(userStates[i] == 0)
{
if(userNames.indexOf(tempData[0]) == -1)
{
userNames[i] = tempData[0];
userStates[i] = 1;
sockets[i].write(SERVER_IN + "Welcome " + tempData[0]+ "!\n"+ SERVER_IN + "Total Users Online: " + userNames.length + "\n"+ USER_IN);
tempData = null;
}
else
{
sockets[i].write(SERVER_IN + "Sorry, name taken.\n"+ SERVER_IN + "Login Name?\n"+ USER_IN);
tempData= null;
}
}
else if(userStates[i] == 1 ) // Inside Chat-O , message to all
{
for(j = 0 ; j < sockets.length ; j++)
{
console.log("message to all");
if(j == i)
{
sockets[j].write(SERVER_IN + userNames[i] +" : " + tempData.join(" ") + "\n" + USER_IN);
}
else
{
sockets[j].write("\n" + SERVER_IN + userNames[i] +" : " + tempData.join(" ") + "\n" + USER_IN);
}
}
}
else
{
sockets[i].write(USER_IN);
}
}
else
{
sockets[i].write(USER_IN);
}
}
}
}
catch(e)
{
console.log("Receiving data exception");
console.log(e);
}
}
}
// function to clean incoming data
function cleanInput(data) {
return data.toString().replace(/(\r\n|\n|\r)/gm,"");
}
/* --------------------------------------------HTTP Server------------------------------------------------------ */
// HTTP server serving a web client
//SetUp Authentication
var auth = require('http-auth');
var basic = auth.basic({
realm: "Westeros"
}, function (username, password, callback) {
callback(username === "gollum" && password === "myprecious");
}
);
//App Setup
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io').listen(http);
var HTTP_PORT = 3000;
console.log(__dirname);
app.use(express.static(__dirname + '/public'));
app.use(auth.connect(basic));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.get('/howto', function(req, res){
res.sendFile(__dirname + '/commands.html');
});
io.on('connection', function(socket){
console.log('Somebody is connecting...');
var tcpClient = new net.Socket();
tcpClient.setEncoding("ascii");
tcpClient.setKeepAlive(true);
//Conect to TCP Server
// HTTP Tunneling
tcpClient.connect(PORT, HOST, function()
{
tcpClient.on('data', function(data) {
socket.emit("httpConnection", data);
});
tcpClient.on('end', function(data) {
console.log('ended session');
});
});
socket.on('newUser', function(userName){
tcpClient.write(userName);
});
socket.on('getRooms', function(cmd){
console.log(cmd);
tcpClient.write(cmd);
});
socket.on('leave', function(cmd){
console.log(cmd);
tcpClient.write(cmd);
});
socket.on('joinRoom', function(room){
console.log(room);
tcpClient.write(room);
});
socket.on('chatMessage', function(msg){
console.log('user sending msg');
tcpClient.write(msg);
});
socket.on('requestPrivate', function(user){
console.log('requesting private chat');
tcpClient.write('/private '+user);
});
socket.on('acceptPrivate', function(user){
console.log('accepting private chat');
tcpClient.write('/accept '+user);
});
socket.on('addRoom', function(room){
console.log('adding chat room');
tcpClient.write('/addroom '+room);
});
socket.on('disconnect', function(){
console.log('user disconnected');
tcpClient.end();
});
});
http.listen(HTTP_PORT, function(){
console.log('HTTP server listening on ' + HTTP_PORT + '...');
});