-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.java
743 lines (644 loc) · 21 KB
/
client.java
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
import java.io.*;
import gnu.getopt.Getopt;
import java.net.Socket;
import java.net.ServerSocket;
import md5.client.MD5;
import md5.client.MD5ImplService;
import java.net.URL;
class client {
/********************* TYPES **********************/
/**
* @brief Return codes for the protocol methods
*/
private static enum RC {
OK,
ERROR,
USER_ERROR
};
/******************* ATTRIBUTES *******************/
private static String _server = null;
private static int _port = -1;
/* Controls the user bound to the client when executing a CONNECT command */
private static String connected_user = null;
/* Instantiate and prepare an empty ServerThread for further connection */
private static ServerThread server_thread = new ServerThread();
/* Variable for storing the IP address of the md5 web service server */
private static String _md5_ws = null;
/********************* METHODS ********************/
/**
* @param user - User name to register in the system
*
* @return OK if successful
* @return USER_ERROR if the user is already registered
* @return ERROR if another error occurred
*/
static RC register(String user)
{
// Write your code here
///////////////////////////////////////////////
/////////////// PROTOCOL ///////////////
///////////////////////////////////////////////
try{
//1. Connect to the server, using the IP and port passed in the command line
Socket sc = new Socket(_server, _port);
DataOutputStream out = new DataOutputStream(sc.getOutputStream());
DataInputStream in = new DataInputStream(sc.getInputStream());
//2. The string "REGISTER" is sent indicating the operation
String operation = new String("REGISTER");
out.writeBytes(operation);
out.write(0); //Insert ASCII 0 at the end
//3. A string of characters is sent with the user to be registered
out.writeBytes(user);
out.write(0);
//4. Check response from the server. If 0, success; if 1 user is previously registered; if 2 other case
byte response = in.readByte();
//5. Close connection
sc.close();
out.close();
in.close();
//Decode the response from the server
switch(response){
case 0:
System.out.println("c> REGISTER OK");
return RC.OK;
case 1:
System.out.println("c> USERNAME IN USE");
return RC.USER_ERROR;
case 2:
System.out.println("c> REGISTER FAIL");
return RC.ERROR;
}
}
catch (java.io.IOException e) {
System.out.println("Exception: " + e);
//e.printStackTrace();
}
System.out.println("c> REGISTER FAIL");
return RC.ERROR;
}
/**
* @param user - User name to unregister from the system
*
* @return OK if successful
* @return USER_ERROR if the user does not exist
* @return ERROR if another error occurred
*/
static RC unregister(String user)
{
///////////////////////////////////////////////
/////////////// PROTOCOL ///////////////
///////////////////////////////////////////////
try{
//1. Connect to the server, using the IP and port passed in the command line
Socket sc = new Socket(_server, _port);
DataOutputStream out = new DataOutputStream(sc.getOutputStream());
DataInputStream in = new DataInputStream(sc.getInputStream());
//2. The string "UNREGISTER" is sent indicating the operation
String operation = new String("UNREGISTER");
out.writeBytes(operation);
out.write(0); //Insert ASCII 0 at the end
//3. A string of characters is sent with the user to be unregistered
out.writeBytes(user);
out.write(0);
//4. Check response from the server. If 0, success; if 1 user does not exist; if 2 other case
byte response = in.readByte();
//5. Close connection
sc.close();
out.close();
in.close();
//Decode the response from the server
switch(response){
case 0:
/* If we try to unregister the user that is currently bound and connected
to the client, it is unbound from the client */
if(connected_user != null){
/* This protects against null pointer exception when a CONNECT command is executed and
the server marks the user as connected, but then the client is terminated without
executing DISCONNECT from the server */
if(connected_user.equals(user)){
connected_user = null;
/* If the unregister also disconnect a user linked to the client (connected and with a
server thread running, kill also the running thread*/
server_thread.kill();
}
}
System.out.println("c> UNREGISTER OK");
return RC.OK;
case 1:
System.out.println("c> USER DOES NOT EXIST");
return RC.USER_ERROR;
case 2:
System.out.println("c> UNREGISTER FAIL");
return RC.ERROR;
}
}
catch (java.io.IOException e) {
System.out.println("Exception: " + e);
//e.printStackTrace();
}
System.out.println("c> UNREGISTER FAIL");
return RC.ERROR;
}
/**
* @param user - User name to connect to the system
*
* @return OK if successful
* @return USER_ERROR if the user does not exist or if it is already connected
* @return ERROR if another error occurred
*/
static RC connect(String user)
{
///////////////////////////////////////////////
/////////////// PROTOCOL ///////////////
///////////////////////////////////////////////
try{
/* Before trying to connect, if a user is already connected, quit the function with RC.ERROR */
if(connected_user != null){
System.out.println("c> CONNECT FAIL");
return RC.ERROR;
}
//1. Connect to the server, using the IP and port passed in the command line
Socket sc = new Socket(_server, _port);
DataOutputStream out = new DataOutputStream(sc.getOutputStream());
DataInputStream in = new DataInputStream(sc.getInputStream());
//2. The string "CONNECT" is sent indicating the operation
String operation = new String("CONNECT");
out.writeBytes(operation);
out.write(0); //Insert ASCII 0 at the end
//3. A string of characters is sent with the user to be connected
out.writeBytes(user);
out.write(0);
/* Create ServerSocket. We provide 0 to assign any available port number and 10 as maximum
number of queued requests */
ServerSocket sock = new ServerSocket(0, 10);
/* Get the port at which the socket is listening */
int port = sock.getLocalPort();
//4. A string is sent with the port number listening in the client
out.writeBytes(String.valueOf(port));
out.write(0);
//5. Check response from the server. If 0, success; if 1 user does not exist; if 2 other case
byte response = in.readByte();
//6. Close connection
sc.close();
out.close();
in.close();
//Decode the response from the server
switch(response){
case 0:
/* Start a new thread where */
server_thread.start(sock);
/* Bind the user to the client */
connected_user = user;
System.out.println("c> CONNECT OK");
return RC.OK;
case 1:
System.out.println("c> CONNECT FAIL, USER DOES NOT EXIST");
return RC.USER_ERROR;
case 2:
System.out.println("c> USER ALREADY CONNECTED");
return RC.USER_ERROR;
case 3:
System.out.println("c> CONNECT FAIL");
return RC.ERROR;
}
}
catch (java.io.IOException e) {
System.out.println("Exception: " + e);
e.printStackTrace();
}
System.out.println("c> CONNECT FAIL");
return RC.ERROR;
}
/**
* @param user - User name to disconnect from the system
*
* @return OK if successful
* @return USER_ERROR if the user does not exist or if it is already disconnected
* @return ERROR if another error occurred
*/
static RC disconnect(String user)
{
///////////////////////////////////////////////
/////////////// PROTOCOL ///////////////
///////////////////////////////////////////////
try{
//1. Connect to the server, using the IP and port passed in the command line
Socket sc = new Socket(_server, _port);
DataOutputStream out = new DataOutputStream(sc.getOutputStream());
DataInputStream in = new DataInputStream(sc.getInputStream());
//2. The string "DISCONNECT" is sent indicating the operation
String operation = new String("DISCONNECT");
out.writeBytes(operation);
out.write(0); //Insert ASCII 0 at the end
//3. A string of characters is sent with the user to be disconnected
out.writeBytes(user);
out.write(0);
//4. Check response from the server. If 0, success; if 1 user does not exist; if 2 other case
byte response = in.readByte();
//5. Close connection
sc.close();
out.close();
in.close();
//Decode the response from the server
switch(response){
case 0:
/* Unbind the user from the client */
connected_user = null;
server_thread.kill();
System.out.println("c> DISCONNECT OK");
return RC.OK;
case 1:
checkAndUnbindUser(user);
System.out.println("c> DISCONNECT FAIL / USER DOES NOT EXIST");
return RC.USER_ERROR;
case 2:
checkAndUnbindUser(user);
System.out.println("c> DISCONNECT FAIL / USER NOT CONNECTED");
return RC.USER_ERROR;
case 3:
checkAndUnbindUser(user);
System.out.println("c> DISCONNECT FAIL");
return RC.ERROR;
}
}
catch (java.io.IOException e) {
System.out.println("Exception: " + e);
//e.printStackTrace();
}
checkAndUnbindUser(user);
System.out.println("c> DISCONNECT FAIL");
return RC.ERROR;
}
private static void checkAndUnbindUser(String user){
/* In case of error in the disconnection process, stop the execution of the thread
and unbind the user from the client as if the disconnection has been made. But if the
disconnect command executed was not executed for the user that is bound to the client
then nothing is done */
if(connected_user != null){
/* Check if the user coincides with the linked user */
if(connected_user.equals(user)){
connected_user = null;
server_thread.kill();
}
}
}
/**
* @param user - Receiver user name
* @param message - Message to be sent
*
* @return OK if the server had successfully delivered the message
* @return USER_ERROR if the user is not connected (the message is queued for delivery)
* @return ERROR the user does not exist or another error occurred
*/
static RC send(String user, String message)
{
String md5;
/* Calculate the MD5 of the message */
try{
/* Build the URL of the web service based on the IP passed in the command */
URL url = new URL(new String("http://" + _md5_ws + "/ws/md5"));
/* Define the MD5 Web service variables */
MD5ImplService md5Service = new MD5ImplService(url);
MD5 md5_ws = md5Service.getMD5ImplPort();
/* Call the web service that calculates de MD5 of the message */
md5 = md5_ws.getMD5(message);
}
catch(Exception e){
/* If exception occurs, nothing is sent to the server. Print error */
System.out.println("c> ERROR , SEND FAIL / ERROR IN MD5");
return RC.ERROR;
}
///////////////////////////////////////////////
/////////////// PROTOCOL ///////////////
///////////////////////////////////////////////
try{
/* If there is not a user connected in the client, return error RC.ERROR */
if(connected_user == null){
System.out.println("c> SEND FAIL");
return RC.ERROR;
}
//1. Connect to the server, using the IP and port passed in the command line
Socket sc = new Socket(_server, _port);
DataOutputStream out = new DataOutputStream(sc.getOutputStream());
DataInputStream in = new DataInputStream(sc.getInputStream());
//2. The string "SEND" is sent indicating the operation
String operation = new String("SEND");
out.writeBytes(operation);
out.write(0); //Insert ASCII 0 at the end
//3. A string of characters is sent with the user that sends the message
out.writeBytes(connected_user);
out.write(0);
//4. A string of characters is sent with the user that receives the message
out.writeBytes(user);
out.write(0);
//5. A string of maximum 256 (including ASCII 0) characters is sent with the message to be sent
out.writeBytes(trimMessage(message)); //Sends a string of 255 characters
out.write(0);
//6. A string of characters is sent with the MD5 hash of the message to be sent
out.writeBytes(md5); //Sends a string of 255 characters
out.write(0);
//7. Check response from the server. If 0, success; if 1 user does not exist; if 2 other case
byte response = in.readByte();
String msg_id = new String();
/* If response is 0 (OK), prepare to read the ID of the message */
if(response == 0){
/* Create BufferedReader for easy reading a string */
/*
BufferedReader inString = new BufferedReader(new InputStreamReader(sc.getInputStream()));
msg_id = inString.readLine();*/
byte ch;
do{
ch = in.readByte();
if (ch != 0) msg_id = msg_id + ((char) ch);
} while(ch != 0);
}
//8. Close connection
sc.close();
out.close();
in.close();
//Decode the response from the server
switch(response){
case 0:
System.out.println("c> SEND OK - MESSAGE " + msg_id);
return RC.OK;
case 1:
System.out.println("c> SEND FAIL / USER DOES NOT EXIST");
return RC.USER_ERROR;
case 2:
System.out.println("c> SEND FAIL");
return RC.ERROR;
}
}
catch (java.io.IOException e) {
System.out.println("Exception: " + e);
//e.printStackTrace();
}
System.out.println("c> SEND FAIL");
return RC.ERROR;
}
/**
* @brief Trims the input message to 255 characters
*
* @param message - String to be trimmed
*
* @return message - Result String
*/
static String trimMessage(String message){
/* Maximum length is of 255 characters because 1 character is reserved for ASCII 0 */
int maxLength = 255;
if(message.length() > maxLength){
message = message.substring(0, maxLength);
}
return message;
}
/**
* @brief Command interpreter for the client. It calls the protocol functions.
*/
static void shell()
{
boolean exit = false;
String input;
String [] line;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (!exit) {
try {
System.out.print("c> ");
input = in.readLine();
line = input.split("\\s");
if (line.length > 0) {
/*********** REGISTER *************/
if (line[0].equals("REGISTER")) {
if (line.length == 2) {
register(line[1]); // userName = line[1]
} else {
System.out.println("Syntax error. Usage: REGISTER <userName>");
}
}
/********** UNREGISTER ************/
else if (line[0].equals("UNREGISTER")) {
if (line.length == 2) {
unregister(line[1]); // userName = line[1]
} else {
System.out.println("Syntax error. Usage: UNREGISTER <userName>");
}
}
/************ CONNECT *************/
else if (line[0].equals("CONNECT")) {
if (line.length == 2) {
connect(line[1]); // userName = line[1] AQUI CREAMOS EL HILO SERVIDOR
} else {
System.out.println("Syntax error. Usage: CONNECT <userName>");
}
}
/********** DISCONNECT ************/
else if (line[0].equals("DISCONNECT")) {
if (line.length == 2) {
disconnect(line[1]); // userName = line[1]
} else {
System.out.println("Syntax error. Usage: DISCONNECT <userName>");
}
}
/************** SEND **************/
else if (line[0].equals("SEND")) {
if (line.length >= 3) {
// Remove first two words
String message = input.substring(input.indexOf(' ')+1);
message = message.substring(message.indexOf(' ')+1);
send(line[1], message); // userName = line[1]
} else {
System.out.println("Syntax error. Usage: SEND <userName> <message>");
}
}
/************** QUIT **************/
else if (line[0].equals("QUIT")){
if (line.length == 1) {
exit = true;
} else {
System.out.println("Syntax error. Use: QUIT");
}
}
/************* UNKNOWN ************/
else {
System.out.println("Error: command '" + line[0] + "' not valid.");
}
}
} catch (java.io.IOException e) {
System.out.println("Exception: " + e);
//e.printStackTrace();
}
}
}
/**
* @brief Prints program usage
*/
static void usage()
{
System.out.println("Usage: java -cp . client -s <server> -p <port>");
}
/**
* @brief Parses program execution arguments
*/
static boolean parseArguments(String [] argv)
{
Getopt g = new Getopt("client", argv, "ds:p:w:");
int c;
String arg;
while ((c = g.getopt()) != -1) {
switch(c) {
//case 'd':
// _debug = true;
// break;
case 's':
_server = g.getOptarg();
break;
case 'p':
arg = g.getOptarg();
_port = Integer.parseInt(arg);
break;
case 'w':
_md5_ws = g.getOptarg();
break;
case '?':
System.out.print("getopt() returned " + c + "\n");
break; // getopt() already printed an error
default:
System.out.print("getopt() returned " + c + "\n");
}
}
if (_server == null)
return false;
if ((_port < 1024) || (_port > 65535)) {
System.out.println("Error: Port must be in the range 1024 <= port <= 65535");
return false;
}
return true;
}
/********************* MAIN **********************/
public static void main(String[] argv)
{
if(!parseArguments(argv)) {
usage();
return;
}
/* Creates a thread that catches Ctrl+C kill command from the CLI and disconnects from the server the
connected user of the client (bound to the client) */
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
if(connected_user != null){
disconnect(connected_user);
}
}
});
shell();
System.out.println("+++ FINISHED +++");
}
}
/********************* SERVERTHREAD **********************/
class ServerThread extends Thread{
private ServerSocket sc; //ServerSocket of the listening thread
private volatile Thread blinker; //Thread of type volatile that will be attached to the ServerThread
private Socket sd;
/**
* @brief Constructor. Starts the server thread and initializes the ServerSocket property
*
* @param sc - Initialized ServerSocket
*
*/
public void start(ServerSocket sc){
blinker = new Thread(this);
blinker.start();
this.sc = sc;
}
/**
* @brief Destroys the server thread
*/
public void kill(){
try{
if(sd != null) this.sd.close();
}
catch(IOException e){
System.out.println("Exception: " + e);
}
blinker = null;
}
/**
* @brief Main execution code sequence of the server thread. Listens to incoming connections
*/
public void run(){
Thread thisThread = Thread.currentThread();
sd = null;
while(blinker == thisThread){
try{
/* Waiting for connection */
sd = this.sc.accept();
DataInputStream msg_in = new DataInputStream(sd.getInputStream());
/* Receive the string encoding the operation */
String operation = new String();
byte ch;
do{
ch = msg_in.readByte();
if (ch != 0) operation = operation + ((char) ch);
} while(ch != 0);
/* Prepare the string for the ID of the message sent/received */
String id = new String();
switch(operation){
case "SEND_MESSAGE":
/* Read the sender username from the socket */
String sender = new String();
do{
ch = msg_in.readByte();
if (ch != 0) sender = sender + ((char) ch);
} while(ch != 0);
/* Read the ID of the received message */
do{
ch = msg_in.readByte();
if (ch != 0) id = id + ((char) ch);
} while(ch != 0);
/* Read the string containing the MD5 of the message */
String md5 = new String();
do{
ch = msg_in.readByte();
if (ch != 0) md5 = md5 + ((char) ch);
} while(ch != 0);
/* Read the string containing the body of the message */
String msg = new String();
do{
ch = msg_in.readByte();
if (ch != 0) msg = msg + ((char) ch);
} while(ch != 0);
/* Prompt */
System.out.println("MESSAGE " + id + " FROM " + sender + ":");
System.out.println("\t" + msg);
System.out.println("\tMD5:");
System.out.println("\t" + md5);
System.out.println("\tEND");
System.out.print("c> ");
break;
case "SEND_MESS_ACK":
/* Read the id of the message being acknowledged */
do{
ch = msg_in.readByte();
if (ch != 0) id = id + ((char) ch);
} while(ch != 0);
System.out.println("SEND MESSAGE " + id + " OK");
System.out.print("c> ");
break;
}
sd.close();
}
catch(Exception e){
System.out.println("Exception: " + e);
//e.printStackTrace();
this.kill();
}
}
/* If the thread exits the loop for any reason, try to close the socket */
try{
sd.close();
}
catch(Exception e){
System.out.println("Exception: " + e);
this.kill();
}
}
}