-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClientHandler.java
55 lines (42 loc) · 1.18 KB
/
ClientHandler.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
40
41
42
43
44
45
46
47
48
49
import java.io.*;
import java.net.*;
import java.util.*;
public class ClientHandler implements Runnable {
Socket socket;
Server server;
BufferedReader reader;
PrintWriter sendClient;
public ClientHandler(Server server, Socket clientSocket) {
try {
this.socket = clientSocket;
this.server = server;
InputStreamReader isReader = new InputStreamReader(socket.getInputStream());
this.reader = new BufferedReader(isReader);
System.out.println("Waiting for client's message");
} catch (Exception ex) {ex.printStackTrace();}
}
public PrintWriter getWriter() {
return sendClient;
}
@Override
public void run() {
String message;
try{
sendClient = new PrintWriter(socket.getOutputStream(), false);
while(!socket.isClosed()) {
if((message = reader.readLine()) != null){
sendEveryone(message);
}
}
}catch(IOException ex) {ex.printStackTrace();}
} // close run method
public void sendEveryone(String message) {
for(ClientHandler client : server.getClients()){
PrintWriter clientOut = client.getWriter();
if(clientOut != null) {
clientOut.println(message);
clientOut.flush();
}
}
} // close sendEveryone method
}