-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.java
More file actions
635 lines (548 loc) · 21.3 KB
/
Client.java
File metadata and controls
635 lines (548 loc) · 21.3 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
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
//new Class Client
public class Client
{
//main running function
public static void main(String[] args) throws IOException
{
//port given by user
int port = Integer.parseInt(args[0]);
//test port
//int port = 5000;
//function to save port for later use
saveConnectionData(port);
//start authentication step
authenticate();
}
//save port to the class and also save address to reduce line length, a lot easier to type 'address' vs InetAddress.getByName("localhost");
//create new UDP socket and save locally. Open-ended port that OS chooses
public static void saveConnectionData(int port) throws SocketException, UnknownHostException
{
socket = new DatagramSocket();
address = InetAddress.getByName("localhost");
serverPort = port;
}
//authentication step function
//waits for server to authorize user
public static void authenticate() throws IOException
{
while(true)
{
Scanner sc = new Scanner(System.in);//new scanner for user input
String name;//username string
System.out.println("Enter username: ");//prompt user for name
name = sc.nextLine();//save user input to string
while (name.length() == 0)//if user enters string of size 0 and continues to do so
{
System.out.println("Enter username of sufficient size: ");//prompt user to enter valid username
name = sc.nextLine();//save and then recheck
}
byte[] buffer = name.getBytes();//save bytes to buffer array
byte[] resBuffer = new byte[1];//new response buffer for what the server responds back with
DatagramPacket data = new DatagramPacket(buffer, buffer.length, address, serverPort);//two packets for outgoing data and incoming response
DatagramPacket response = new DatagramPacket(resBuffer, resBuffer.length, address, serverPort);
//send username as a packet
socket.send(data);
//receive response and save to resBuffer
socket.receive(response);
if(response.getData()[0] == 0)//account creation, query if user wants to make account and then query password
{
//send off response back to server on whether user wants to create account with that name
//if response is false -> break loop
//if true -> server will request password as it already has the name of the account
System.out.println("No account found, Do you wish to create an account with that name? (YES/NO)");
String query = sc.nextLine();
accountCreation(query);//give query to function and determine user response
}
else if(response.getData()[0] == 1)//already logged in, try again
{
System.out.println("User is already logged in");
}
else if(response.getData()[0] == 2)//query password
{
//enter new function to send back password and check if password is incorrect
passwordQuery();
}
}
}
//function to indicate that login is successful based off responses from server
//starts server commands function
public static void loginSuccess() throws IOException
{
System.out.println("Welcome to the forum");
serverCommands();
}
//function to determine if user would like to create account
//proceeds to create if YES is given
//if NO or some other input, then return to log in function
public static void accountCreation(String query) throws IOException
{
byte[] resBuffer = new byte[1];//new response buffer
DatagramPacket response = new DatagramPacket(resBuffer, resBuffer.length, address, serverPort);//new packet to give to server
Scanner sc = new Scanner(System.in);//check if user says YES or otherwise
if(query.contains("YES"))//if yes
{
resBuffer[0] = 1;//write 1 to buffer at index 0
socket.send(response);//send
socket.receive(response);//receive response from server
System.out.println("Enter new password: ");//query for new password from user
String password = sc.nextLine();//read and save user input
byte[] buffer = password.getBytes();//write password to byte array
DatagramPacket data = new DatagramPacket(buffer, buffer.length, address, serverPort);//package as data packet
socket.send(data);//send password to server
loginSuccess();//indicate login was successful
}
else//NO or otherwise
{
response = new DatagramPacket(resBuffer, resBuffer.length, address, serverPort);//write response containing 0 from instantiation at index 0
socket.send(response);//send to server indicating to return to login page
}
}
//query for password upon giving server username
public static void passwordQuery() throws IOException
{
byte[] resBuffer = new byte[1];//defaults to 0
Scanner sc = new Scanner(System.in);//new scanner
DatagramPacket response = new DatagramPacket(resBuffer, resBuffer.length, address, serverPort);//new packet to give to server
System.out.println("Enter password: ");//prompt user for password for preexisting account
String password = sc.nextLine();//read data
byte[] buffer = password.getBytes();//save to buffer
DatagramPacket data = new DatagramPacket(buffer, buffer.length, address, serverPort);//package as packet
socket.send(data);//give to server
socket.receive(response);//receive response
//check validity
if(response.getData()[0] == 1)//if 1
{
loginSuccess();//successful
}
else
{
System.out.println("Wrong password! Try again!");//else return to log in after telling user login has failed
}
}
//server command function
public static void serverCommands() throws IOException
{
//loop eternally until exit is given
Scanner scanner = new Scanner(System.in);//new scanner
while(true)//loop indefinitely
{
printCommands();//print list of commands to user
String data = scanner.nextLine();//scan next line
data = data.trim();//trim any whitespace
if(!socket.isConnected())//check if socket is connected
{
socket.connect(address, serverPort);//connect if not
}
if((data.length() >= 3) && isWellFormedString(data))//check if string is of at least size 3 and is a wellFormed String for commands to give to server
{
String command = data.substring(0, 3);//substring from 0 to 3 for every command
switch (command)//give switch to compare the commands of all ten types
{
case "XIT":
caseXIT(data);
break;
case "CRT":
caseCRT(data);
break;
case "MSG":
{
caseMSG(data);
break;
}
case "LST":
{
caseLST(data);
break;
}
case "RDT":
{
caseRDT(data);
break;
}
case "EDT":
{
caseEDT_DLT(1, data);//cheap flag because both are very similar
break;
}
case "DLT":
{
caseEDT_DLT(2, data);//cheap flag because both are very similar
break;
}
case "RMV":
{
caseRMV(data);
break;
}
case "UPD":
{
caseUPD(data);
break;
}
case "DWN":
{
caseDWN(data);
break;
}
}
}
else
{
System.out.println("Try again");//try again if is not a well-formed string or size is less than 3
}
}
}
//check well formed string
//could be made shorted quite easily, just ran out of time
public static boolean isWellFormedString(String input)
{
String command = input.substring(0, 3);//new substring for checking commands
int numberOfWS = input.length() - input.replaceAll(" ","").length();//save whitespace count
if(command.equals("XIT") || command.equals("LST") && input.length() == 3)//if these commands and the length is of size 3
{
return true;//return true
}
else if(command.equals("CRT") || command.equals("RDT") || command.equals("RMV"))//if these commands
{
//check whitespace count where it should equal one
//if ws == 1 and exists at index 3 and the length of string 'input' from index 4 to max length is > 0
//return true and valid
return numberOfWS == 1 && input.charAt(3) == ' ' && input.substring(4).length() > 0;
}
else if(command.equals("MSG") || command.equals("DLT") || command.equals("UPD") || command.equals("DWN") || command.equals("EDT"))//else if these commands
{
if(numberOfWS == 2 && input.charAt(3) == ' ' && input.substring(4).length() > 0)//same as before but with 2 WS
{
int secondWS;
for(secondWS = 4; secondWS < input.length(); secondWS++)
{
if(input.charAt(secondWS) == ' ')//finding second WS location
{
break;
}
}
//from second WS the string length is > 0
if(input.substring(secondWS).length() > 0)
{
if(!command.equals("DLT"))//only if not DLT command
{
return true;//return true
}
else if(isNumberInString(input.substring(secondWS+1))) return true;//now check if 2nd word in DLT command given can be converted to an integer for the server and return true if possible
}
}
//now check if command is MSG and number of WS is >= as MSG and EDT can have an undefined WS count max but must be a minimum of 2 for MSG and 3 for EDT
else if(command.equals("MSG") && numberOfWS >= 2 && input.charAt(3) == ' ' && input.substring(4).length() > 0)
{
int secondWS;//find second WS
for(secondWS = 4; secondWS < input.length(); secondWS++)
{
if(input.charAt(secondWS) == ' ')
{
break;
}
}
if(input.substring(secondWS).length() > 0) return true;//check if length of word is greater than 0 from secondWS
}
else if(numberOfWS >= 3 && input.charAt(3) == ' ' && input.substring(4).length() > 0)//check if number of WS is greater than of eq to 3 and other checks from above
{
int secondWS;//find second WS
for(secondWS = 4; secondWS < input.length(); secondWS++)
{
if(input.charAt(secondWS) == ' ')
{
break;
}
}
int thirdWS;//find third ws
for(thirdWS = secondWS+1; thirdWS < input.length(); thirdWS++)
{
if(input.charAt(thirdWS) == ' ')
{
break;
}
}
//if is a number at 3rd word and string from index of 3rd word is greater than 0
if(isNumberInString(input.substring(secondWS+1, thirdWS)) && input.substring(thirdWS).length() > 0)
{
return true;//return true
}
}
}
//else give error and return false
System.out.println("Wrong input! Try Again");
return false;
}
//check if string can be formed into number
public static boolean isNumberInString(String s)
{
try//try
{
Integer.parseInt(s);//attempt
return true;//return true if this part is reached
}
catch (NumberFormatException e)//catch failure
{
return false;
}
}
//case XIT command
public static void caseXIT(String data) throws IOException
{
//send command to server
sendCommand(data);
System.out.println("Goodbye!");//give goodbye to user
System.exit(0);//exit client
}
//case CRT command
public static void caseCRT(String data) throws IOException
{
//send command to server
sendCommand(data);
byte[] response = receiveResponse();
if (response[0] == 1)
{
String name = data.substring(4);
System.out.println("Thread " + name + " was created!");
}
else
{
System.out.println("Thread Already Exists!");
}
}
public static void caseMSG(String data) throws IOException
{
//send command to server
sendCommand(data);
byte[] response = receiveResponse();
if (response[0] == 1)
{
System.out.println("Message posted");
}
else
{
System.out.println("No such Thread");
}
}
public static void caseLST(String data) throws IOException
{
//send command to server
sendCommand(data);
byte[] newData = receiveData();
if (newData[0] == 0)
{
System.out.println("No Threads exist!");
}
else
{
String list = new String(newData, 0, newData.length).trim();
System.out.println("The list of active Threads:");
System.out.println(list);
}
}
public static void caseRDT(String data) throws IOException
{
//send command to server
sendCommand(data);
byte[] newData = receiveData();
if (newData[0] == 0)
{
System.out.println("No such Thread");
}
else
{
String thread = new String(newData, 0, newData.length).trim();
if(thread.isEmpty() || thread.isBlank())
{
System.out.println("Thread is empty!");
}
else
{
System.out.println(thread);
}
}
}
public static void caseEDT_DLT(int type, String data) throws IOException
{
//send command to server
sendCommand(data);
System.out.println(data);
byte[] response = receiveResponse();
if (response[0] == 0)
{
System.out.println("No such Thread");
}
if (response[0] == 1)
{
System.out.println("Given message number not valid");
}
if (response[0] == 2)
{
System.out.println("Current user does not have access to that");
}
if (response[0] == 3 && type == 1)
{
System.out.println("Successfully edited message");
}
if (response[0] == 3 && type == 2)
{
System.out.println("Successfully deleted message");
}
}
public static void caseRMV(String data) throws IOException
{
//send command to server
sendCommand(data);
byte[] response = receiveResponse();
if (response[0] == 0)
{
System.out.println("No such Thread");
}
else if (response[0] == 1)
{
System.out.println("Current user does not have access to that");
}
else if (response[0] == 2)
{
System.out.println("Successfully removed thread!");
}
}
public static void caseUPD(String data) throws IOException
{
//send command to server
sendCommand(data);
String fileName = getNextWord(data);
byte[] response = receiveData();
if (response[0] == 2)
{
sendFile(fileName);
System.out.println("File Uploaded!");
}
else if (response[0] == 1)
{
System.out.println("File already exists on this thread!");
}
else if (response[0] == 0)
{
System.out.println("No such Thread");
}
}
public static void caseDWN(String data) throws IOException
{
//send command to server
sendCommand(data);
String fileName = getNextWord(data);
byte[] response = receiveData();
if (response[0] == 2)
{
receiveFile(fileName);
System.out.println("File Downloaded!");
}
else if (response[0] == 1)
{
System.out.println("File does not exist on Server!");
}
else if (response[0] == 0)
{
System.out.println("No such Thread");
}
}
public static void sendFile(String fileName) throws IOException
{
socket.disconnect();
Socket tcp_socket = new Socket("localhost", serverPort);
tcp_socket.getOutputStream();
InputStream inputStream = null;
OutputStream fileOutputStream = null;
byte[] myByteArray = new byte[8192];
try
{
inputStream = new FileInputStream(fileName);
fileOutputStream = tcp_socket.getOutputStream();
int count;
while ((count = inputStream.read(myByteArray)) > 0)
{
fileOutputStream.write(myByteArray, 0, count);
}
}
finally
{
assert fileOutputStream != null;
fileOutputStream.close();
inputStream.close();
tcp_socket.close();
}
}
public static void receiveFile(String fileName) throws IOException
{
socket.disconnect();
Socket tcp_socket = new Socket("localhost", serverPort);
tcp_socket.getInputStream();
InputStream inputStream = null;
OutputStream fileOutputStream = null;
byte[] myByteArray = new byte[8192];
try
{
fileOutputStream = new FileOutputStream(fileName);
inputStream = tcp_socket.getInputStream();
int count;
while ((count = inputStream.read(myByteArray)) > 0)
{
fileOutputStream.write(myByteArray, 0, count);
}
}
finally
{
assert fileOutputStream != null;
fileOutputStream.close();
assert inputStream != null;
inputStream.close();
tcp_socket.close();
}
}
public static void sendCommand(String data) throws IOException
{
byte[] commandBuffer = data.getBytes(StandardCharsets.UTF_8);
DatagramPacket commandPacket = new DatagramPacket(commandBuffer, commandBuffer.length, address, serverPort);
socket.send(commandPacket);
}
public static byte[] receiveResponse() throws IOException
{
byte[] resBuffer = new byte[1];//defaults to 0
DatagramPacket responsePacket = new DatagramPacket(resBuffer, resBuffer.length, address, serverPort);
socket.receive(responsePacket);
return resBuffer;
}
public static byte[] receiveData() throws IOException
{
byte[] resBuffer = new byte[512];//defaults to 0
DatagramPacket responsePacket = new DatagramPacket(resBuffer, resBuffer.length, address, serverPort);
socket.receive(responsePacket);
return resBuffer;
}
public static String getNextWord(String sentence)
{
int indexOfEndOFfThreadTitle = 4;
for (int i = 4; i < sentence.length(); i++)
{
if (sentence.charAt(i) == ' ')
{
indexOfEndOFfThreadTitle = i;
break;
}
}
return sentence.substring(indexOfEndOFfThreadTitle + 1);
}
public static void printCommands()
{
System.out.println(commandList);
}
private static DatagramSocket socket;
private static InetAddress address;
private static int serverPort;
private static final String commandList = System.getProperty("line.separator") + "Enter one of the following commands: CRT," + System.getProperty("line.separator") + "MSG, DLT, EDT, LST, RDT, UPD, DWN, RMV," + System.getProperty("line.separator") + "XIT:" + System.getProperty("line.separator");
}