-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadThread.java
More file actions
55 lines (50 loc) · 1.9 KB
/
ReadThread.java
File metadata and controls
55 lines (50 loc) · 1.9 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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
/*
This thread is responsible for reading server's input and printing it to the
console.
It runs in an infinite loop until the client disconnects from the server.
*/
public class ReadThread extends Thread{
private BufferedReader reader;
private Socket socket;
private ChatClient client;
public ReadThread(Socket socket, ChatClient client) {
this.socket = socket;
this.client = client;
try {
InputStream input = socket.getInputStream();
reader = new BufferedReader(new InputStreamReader(input));
} catch (IOException ex) {
System.out.println("Error getting input stream: " + ex.getMessage());
ex.printStackTrace();
}
}
public void run() {
while (true) {
try {
String response = reader.readLine();
System.out.println("\n" + response);
//prints the username after displaying the server's message
if (client.getUserName() != null) {
System.out.println("[" + client.getUserName() + "]: ");
}
} catch (IOException ex) {
System.out.println("Error reading from server: " + ex.getMessage());
ex.printStackTrace();
break;
}
}
}
}
/*
This is a Java class called "ReadThread" that reads incoming messages from a
socket connection. It creates an input stream from the socket's input stream,
and wraps it in a BufferedReader for more efficient reading. The run method
reads lines from the input stream in a loop, and prints them to the console
along with the client's username, if it's available. If there's an IOException,
it will print the error message, and the loop will be broken.
*/