-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatServer.java
More file actions
executable file
·683 lines (505 loc) · 14.9 KB
/
Copy pathChatServer.java
File metadata and controls
executable file
·683 lines (505 loc) · 14.9 KB
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
/*
Author: Carlos Miguel Fernando
GitHub: https://github.com/ByteThis
LinkedIn: https://www.linkedin.com/in/0xcmf
*/
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
class User{
String name;
String currRoom;
String status;
Socket socket;
public User(Socket s){
socket = s;
currRoom = null;
name = "";
status = "init";
}
}
class Room{
String roomName;
LinkedList<User> online = new LinkedList<User>();
Room(String s){
roomName = s;
}
}
public class ChatServer{
static LinkedList<User> people = new LinkedList<User>();
static LinkedList<Room> rooms = new LinkedList<Room>();
// A pre-allocated buffer for the received data
static private final ByteBuffer buffer = ByteBuffer.allocate( 16384 );
// Decoder for incoming text -- assume UTF-8
static private final Charset charset = Charset.forName("UTF8");
static private final CharsetDecoder decoder = charset.newDecoder();
static public void main( String args[] ) throws Exception {
// Parse port from command line
int port = Integer.parseInt( args[0] );
try {
// Instead of creating a ServerSocket, create a ServerSocketChannel
ServerSocketChannel ssc = ServerSocketChannel.open();
// Set it to non-blocking, so we can use select
ssc.configureBlocking( false );
// Get the Socket connected to this channel, and bind it to the
// listening port
ServerSocket ss = ssc.socket();
InetSocketAddress isa = new InetSocketAddress( port );
ss.bind( isa );
// Create a new Selector for selecting
Selector selector = Selector.open();
// Register the ServerSocketChannel, so we can listen for incoming
// connections
ssc.register( selector, SelectionKey.OP_ACCEPT );
System.out.println( "Listening on port "+port );
while (true) {
// See if we've had any activity -- either an incoming connection,
// or incoming data on an existing connection
int num = selector.select();
// If we don't have any activity, loop around and wait again
if (num == 0) {
continue;
}
// Get the keys corresponding to the activity that has been
// detected, and process them one by one
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> it = keys.iterator();
while (it.hasNext()) {
// Get a key representing one of bits of I/O activity
SelectionKey key = it.next();
// What kind of activity is it?
if ((key.readyOps() & SelectionKey.OP_ACCEPT) ==
SelectionKey.OP_ACCEPT) {
// It's an incoming connection. Register this socket with
// the Selector so we can listen for input on it
Socket s = ss.accept();
people.add(new User(s));
System.out.println( "Got connection from "+s );
// Make sure to make it non-blocking, so we can use a selector
// on it.
SocketChannel sc = s.getChannel();
sc.configureBlocking(false);
// Register it with the selector, for reading
sc.register( selector, SelectionKey.OP_READ );
} else if ((key.readyOps() & SelectionKey.OP_READ) ==
SelectionKey.OP_READ) {
SocketChannel sc = null;
try {
// It's incoming data on a connection -- process it
sc = (SocketChannel) key.channel();
boolean ok = processInput(sc);
// If the connection is dead, remove it from the selector
// and close it
if (!ok) {
key.cancel();
Socket s = null;
Room room = null;
try {
s = sc.socket();
System.out.println( "Closing connection to "+s );
for(User u : people){
if(u.socket.equals(s)){
room=checkRoom(u.currRoom);
if(room != null){
chatEvents(u, room, "", "join");
room.online.remove(u);
if(room.online.isEmpty()){
rooms.remove(room);
}
}
people.remove(u);
break;
}
}
s.close();
} catch( IOException ie ) {
System.err.println( "Error closing socket "+s+": "+ie );
}
}
} catch( IOException ie ) {
// On exception, remove this channel from the selector
key.cancel();
try {
sc.close();
} catch( IOException ie2 ) { System.out.println( ie2 ); }
System.out.println( "Closed "+sc );
}
}
}
// We remove the selected keys, because we've dealt with them.
keys.clear();
}
} catch( IOException ie ) {
System.err.println( ie );
}
}
public static void sendMessage(User u, String text){
text+='\n';
try{
u.socket.getChannel().write(ByteBuffer.wrap(text.getBytes()));
} catch (IOException e){
System.out.println("Erro on sendMessage;");
e.printStackTrace();
}
}
static boolean checkName(String n){
if(people.isEmpty()){
return false;
}
for(User u : people){
if (u.name.equals(n)){
return false;
}
}
return true;
}
static Room checkRoom(String n){
for(Room r : rooms) {
if (r.roomName.equals(n))
return r;
}
return null;
}
static void chatEvents(User u, Room r, String text, String event) throws IOException{
FileWriter fw = new FileWriter(r.roomName + "_log.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter writer = new PrintWriter(bw);
DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
Calendar calobj = Calendar.getInstance();
//System.out.println();
switch (event){
case "msg":
writer.print(calobj.getTime() + "\t>> " + u.name + ": " + text + "\n");
writer.close();
text="MESSAGE " + u.name + " " + text + "\n";
break;
case "join":
writer.print(calobj.getTime() + "\tUSER " + u.name + " HAS JOINED ROOM " + r.roomName + "\n");
writer.close();
text="JOINED " + u.name + "\n";
break;
case "leave":
writer.print(calobj.getTime() + "\tUSER " + u.name + " HAS LEFT ROOM " + r.roomName + "\n");
writer.close();
text="LEFT " + u.name + "\n";
break;
case "newname":
writer.print(calobj.getTime() + "\tUSER " + u.name + " HAS CHANGED NAME TO " + text + "\n");
writer.close();
text="NEWNICK " + u.name + " " + text + "\n";
break;
default:
System.out.println("ERRO on chatEvents");
break;
}
for(User usr : r.online){
if(event=="newname"){
if(usr.name != u.name){
try{
usr.socket.getChannel().write(ByteBuffer.wrap(text.getBytes()));
} catch(IOException e){
System.out.println("Erro sending chatEvents;");
e.printStackTrace();
}
}
}
else{
try{
usr.socket.getChannel().write(ByteBuffer.wrap(text.getBytes()));
} catch(IOException e){
System.out.println("Erro sending chatEvents;");
e.printStackTrace();
}
}
}
}
static void pvtMsg(String from, String to, String msg) {
msg = "(PRIVATE) " + from + ": " + msg + '\n';
for (User i : people) {
try {
if (i.name.equals(to))
i.socket.getChannel().write(ByteBuffer.wrap(msg.getBytes()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Just read the message from the socket and send it to stdout
static private boolean processInput(SocketChannel sc) throws IOException {
String message;
Room temp;
// Read the message to the buffer
buffer.clear();
sc.read( buffer );
buffer.flip();
// If no data, close the connection
if (buffer.limit()==0) {
return false;
}
User us = null;
for (User i : people){
if (i.socket.equals(sc.socket())){
us=i;
break;
}
}
// Decode and print the message to stdout
message = decoder.decode(buffer).toString();
System.out.println( message );
String arr[] = message.split("\\s+");
if (message.length()==0){
return true;
}
//Init status
if (us.status.equals("init")){
if (arr.length == 2 && arr[0].equals("/nick")) {
//name available
if (checkName(arr[1])) {
us.name = arr[1];
us.status = "outside";
System.out.println("OK");
sendMessage(us, "OK");
}
//name in use
else {
System.out.println("ERROR");
sendMessage(us, "ERROR");
}
return true;
}
if (arr.length == 1 && arr[0].equals("/bye")) {
sendMessage(us, "BYE");
return false;
}
System.out.println("ERROR");
sendMessage(us, "ERROR");
return true;
}
// ##### OUTSIDE A ROOM #####
if (us.status.equals("outside")) {
//Get online user's list
if (arr.length == 1 && arr[0].equals("/online")) {
System.out.println("\n\nONLINE USERS\n________________");
sendMessage(us, "\n\nONLINE USERS\n________________");
for(User u : people){
System.out.println(u.name);
sendMessage(us, u.name);
}
return true;
}
//Get online user's list of a room
if (arr.length == 2 && arr[0].equals("/online")) {
Room rtest = null;
rtest = checkRoom(arr[1]);
//room exists
if (rtest != null) {
System.out.println("\n\nONLINE USERS IN ROOM " + rtest.roomName + "\n________________");
sendMessage(us, "\n\nONLINE USERS IN ROOM " + rtest.roomName + "\n________________");
for(User u : rtest.online){
System.out.println(u.name);
sendMessage(us, u.name);
}
}
else {
System.out.println("ERROR: ROOM '" + arr[1] + "'' DOES NOT EXIST");
sendMessage(us, "ERROR: ROOM '" + arr[1] + "'' DOES NOT EXIST");
}
return true;
}
if (arr.length == 2 && arr[0].equals("/nick")) {
//name available
if (checkName(arr[1])) {
us.name = arr[1];
System.out.println("OK");
sendMessage(us, "OK");
}
//name in use
else {
System.out.println("ERROR");
sendMessage(us, "ERROR");
}
return true;
}
if (arr.length == 2 && arr[0].equals("/join")) {
Room r = null;
r = checkRoom(arr[1]);
//room exists
if (r != null) {
us.status = "inside";
us.currRoom = arr[1];
sendMessage(us, "OK");
//notify channel
chatEvents(us, r, "", "join");
r.online.add(us);
}
//room does not exist
else {
r = new Room(arr[1]);
rooms.add(r);
us.status = "inside";
us.currRoom = arr[1];
sendMessage(us, "OK");
chatEvents(us, r, "", "join");
r.online.add(us);
}
return true;
}
if (arr.length == 1 && arr[0].equals("/bye")) {
sendMessage(us, "BYE");
return false;
}
//private messages
if (arr.length >= 3 && arr[0].equals("/priv")) {
//person exists
if (!checkName(arr[1])){
sendMessage(us, "OK");
String pvtTxt = "";
for (int i = 2; i < arr.length; i++) {
pvtTxt = pvtTxt + " " + arr[i];
}
pvtMsg(us.name, arr[1], pvtTxt);
}
else {
System.out.println("ERROR");
sendMessage(us, "ERROR");
}
return true;
}
System.out.println("ERROR");
sendMessage(us, "ERROR");
return true;
}
// ##### END OF OUTSIDE A ROOM #####
// ##### INSIDE A ROOM #####
if (us.status.equals("inside")) {
Room r = checkRoom(us.currRoom);
//leave current room
if (arr.length == 1 && arr[0].equals("/leave")) {
sendMessage(us, "OK");
temp = r;
r.online.remove(us);
chatEvents(us, temp, "", "leave");
us.status = "outside";
us.currRoom = null;
return true;
}
else if (arr.length == 1 && arr[0].equals("/bye")) {
sendMessage(us, "BYE");
temp = r;
//remove from room
r.online.remove(us);
chatEvents(us, temp, "", "leave");
us.currRoom = null;
return false;
}
//Get online user's list
if (arr.length == 1 && arr[0].equals("/online")) {
System.out.println("\n\nONLINE USERS\n________________");
sendMessage(us, "\n\nONLINE USERS\n________________");
for(User u : people){
System.out.println(u.name);
sendMessage(us, u.name);
}
return true;
}
//Get online user's list of a room
if (arr.length == 2 && arr[0].equals("/online")) {
Room rtest = null;
rtest = checkRoom(arr[1]);
//room exists
if (rtest != null) {
System.out.println("\n\nONLINE USERS IN ROOM " + rtest.roomName + "\n________________");
sendMessage(us, "\n\nONLINE USERS IN ROOM " + rtest.roomName + "\n________________");
for(User u : rtest.online){
System.out.println(u.name);
sendMessage(us, u.name);
}
}
else {
System.out.println("ERROR: ROOM '" + arr[1] + "'' DOES NOT EXIST");
sendMessage(us, "ERROR: ROOM '" + arr[1] + "'' DOES NOT EXIST");
}
return true;
}
else if (arr.length == 2 && arr[0].equals("/nick")) {
//new name
if (checkName(arr[1])) {
//user the "x has changed name to y"
chatEvents(us, r, arr[1], "newname");
us.name = arr[1];
System.out.println("OK");
sendMessage(us, "OK");
}
//name exists
else {
System.out.println("ERROR");
sendMessage(us, "ERROR");
}
return true;
}
else if (arr.length == 2 && arr[0].equals("/join")) {
Room rchange = null;
rchange = checkRoom(arr[1]);
//room exists
if (rchange != null) {
sendMessage(us, "OK");
temp = r;
r.online.remove(us);
chatEvents(us, temp, "", "leave");
chatEvents(us, rchange, "", "join");
rchange.online.add(us);
us.currRoom = arr[1];
}
//new room
else {
rchange = new Room(arr[1]);
rooms.add(rchange);
sendMessage(us, "OK");
temp = r;
//remove from old room
r.online.remove(us);
chatEvents(us, temp, "", "leave");
//add to new room
chatEvents(us, rchange, "", "join");
rchange.online.add(us);
us.currRoom = arr[1];
}
return true;
}
//private messages
else if (arr.length >= 3 && arr[0].equals("/priv")) {
//person exists
if (!checkName(arr[1])) {
sendMessage(us, "OK");
String pvtTxt = "";
for (int i = 2; i < arr.length; i++) {
pvtTxt = pvtTxt + " " + arr[i];
}
pvtMsg(us.name, arr[1], pvtTxt);
}
else {
System.out.println("ERROR");
sendMessage(us, "ERROR");
}
return true;
}
// escape the '/'' char
else if(message.charAt(0) == '/'){
chatEvents(us, r, message.substring(1), "msg");
}
else{
chatEvents(us, r, message, "msg");
}
return true;
}
return true;
}
//fim classe
}