-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClient.java
39 lines (34 loc) · 1.39 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
import java.io.*;
import java.net.*;
public class Client {
private static final String HOST = "localhost";
private static final int PORT = 1234;
public static void main(String[] args) throws IOException {
try (Socket socket = new Socket(HOST, PORT);
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream())) {
int clientId = input.readInt();
System.out.println("Client started with ID: " + clientId);
new Thread(() -> {
try {
while (!socket.isClosed()) {
String serverMessage = input.readUTF();
System.out.println(serverMessage); // Print messages from server
}
} catch (IOException e) {
System.out.println("Connection closed.");
}
}).start();
try {
while (!socket.isClosed()) {
String aliveMessage = "I am alive " + clientId;
output.writeUTF(aliveMessage);
output.flush();
Thread.sleep(3000);
}
} catch (InterruptedException e) {
System.out.println("Client interrupted.");
}
}
}
}