-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatClient2.java
More file actions
52 lines (45 loc) · 1.85 KB
/
ChatClient2.java
File metadata and controls
52 lines (45 loc) · 1.85 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
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ChatClient2 {
private static volatile boolean writeFlag = true;
private static volatile boolean readFlag = true;
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 5000);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Scanner scanner = new Scanner(System.in)) {
// Write thread - sends user input to the server
Thread writeThread = new Thread(() -> {
while (writeFlag) {
String message = scanner.nextLine();
out.println(message);
if (message.equalsIgnoreCase("bye")) {
writeFlag = false;
}
}
});
// Read thread - receives messages from the server
Thread readThread = new Thread(() -> {
try {
while (readFlag) {
String response = in.readLine();
if (response == null || response.equalsIgnoreCase("bye")) {
readFlag = false;
break;
}
System.out.println("Server: " + response);
}
} catch (IOException e) {
System.out.println("Connection closed.");
}
});
writeThread.start();
readThread.start();
writeThread.join();
readThread.join();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}