-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.java
82 lines (68 loc) · 2.87 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
package MyChat;
import java.io.*;
import java.net.*;
import java.util.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
class Client {
static Socket clientSocket;
public static void main(String[] args) throws Exception {
String defaultHost = "127.0.0.1";
int defaultPort = 1025;
connectToServer(defaultHost, defaultPort);
}
// Connects to the server using the specified host address and port number
private static void connectToServer(String hostAddress, int portNumber) throws Exception {
clientSocket = new Socket(hostAddress, portNumber);
if (clientSocket != null) {
displayConnectionDetails();
handleServerResponse();
sendClientMessage();
} else {
System.err.println("\n [Client Connection] Error Occurred \n");
}
}
// Displays the details of the established connection
private static void displayConnectionDetails() throws InterruptedException {
System.out.println("\n [ Secure Connection: " + clientSocket.getLocalSocketAddress() + " ] "
+ DateTimeFormatter.ofPattern("E, dd-MMM-yyyy/HH:mm:ss").format(LocalDateTime.now())
+ " (" + TimeZone.getDefault().getDisplayName() + ") ");
Thread.sleep(2000);
}
/**
* Handles the server's responses by creating a new thread
* Within the thread, it reads input from the server's input stream and prints it to the console
*/
private static void handleServerResponse() {
Thread serverThread = new Thread(() -> {
int responseLine;
try {
DataInputStream inputStream = new DataInputStream(clientSocket.getInputStream());
while ((responseLine = inputStream.read()) != -1) {
System.out.print((char) responseLine);
// if (responseLine.indexOf("Server Disconnected") != -1)
// System.exit(0);
}
} catch (IOException exc) {
exc.printStackTrace();
}
});
serverThread.start();
}
/**
* Reads client input from the command line and sends it to the server through the client socket's output stream
* Repeats the process until the client enters a null value
*/
private static void sendClientMessage() {
String replyLine;
try {
BufferedReader clientInput = new BufferedReader(new InputStreamReader(System.in));
PrintStream outputStream = new PrintStream(clientSocket.getOutputStream());
while ((replyLine = clientInput.readLine()) != null) {
outputStream.println(replyLine);
}
} catch (IOException exc) {
exc.printStackTrace();
}
}
}