-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatClient.java
More file actions
39 lines (35 loc) · 1.38 KB
/
ChatClient.java
File metadata and controls
39 lines (35 loc) · 1.38 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
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ChatClient {
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)) {
System.out.println("Connected to Chat Server.");
// Start a thread to listen for incoming messages
new Thread(() -> {
try {
String serverMessage;
while ((serverMessage = in.readLine()) != null) {
System.out.println(serverMessage);
}
} catch (IOException e) {
System.out.println("Disconnected from server.");
}
}).start();
// User input handling
while (true) {
String userInput = scanner.nextLine();
out.println(userInput);
if (userInput.equalsIgnoreCase("exit")) {
System.out.println("Disconnecting...");
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}