-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWriteThread.java
More file actions
55 lines (46 loc) · 1.63 KB
/
WriteThread.java
File metadata and controls
55 lines (46 loc) · 1.63 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.Console;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
/*
This thread is responsible for reading user's input and send it to the server.
It runs in an infinite loop until the user types 'bye' to quit.
*/
public class WriteThread extends Thread {
private PrintWriter writer;
private Socket socket;
private ChatClient client;
public WriteThread(Socket socket, ChatClient client) {
this.socket = socket;
this.client = client;
try {
OutputStream output = socket.getOutputStream();
writer = new PrintWriter(output, true);
} catch (IOException ex) {
System.out.println("Error getting output stream: " + ex.getMessage());
ex.printStackTrace();
}
}
public void run() {
//System.console() used to read inout from the user
Console console = System.console();
//console.readLine() used to prompt the user to enter their name and
// messages to send to the server
String userName = console.readLine("\nEnter your name: ");
client.setUserName(userName);
writer.println(userName);
String text;
do {
text = console.readLine("[" + userName + "]: ");
// writer.println is used to send the user's name and message to
// the server
writer.println(text);
} while (!text.equals("bye"));
try {
socket.close();
} catch (IOException ex) {
System.out.println("Error writing to server: " + ex.getMessage());
}
}
}