-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClientHandler.java
80 lines (72 loc) · 2.15 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ClientHandler implements Runnable{
public static ArrayList<ClientHandler> clientHandlers = new ArrayList<>();
private Socket socket;
private BufferedReader bufferedReader;
private BufferedWriter bufferedWriter;
private String clientUsername;
public ClientHandler(Socket socket) {
try{
this.socket = socket;
this.bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
this.clientUsername = bufferedReader.readLine();
clientHandlers.add(this);
broadcastMessage("Server: " + this.clientUsername + " has joined the chat.");
}catch(Exception e) {
closeEverything(socket, bufferedWriter, bufferedReader);
}
}
@Override
public void run(){
String message;
while(socket.isConnected()){
try{
message = bufferedReader.readLine();
if(message.equals("exit")){
closeEverything(socket, bufferedWriter, bufferedReader);
break;
}
broadcastMessage(message);
}catch(Exception e){
closeEverything(socket, bufferedWriter, bufferedReader);
break;
}
}
}
public void broadcastMessage(String messageToSend){
for(ClientHandler clientHandler : clientHandlers){
try{
clientHandler.bufferedWriter.write(messageToSend);
clientHandler.bufferedWriter.newLine();
clientHandler.bufferedWriter.flush();
}catch(Exception e){
closeEverything(socket, bufferedWriter, bufferedReader);
}
}
}
public void removeClientHandler(){
clientHandlers.remove(this);
broadcastMessage("Server: " + this.clientUsername + " has left the chat.");
}
public void closeEverything(Socket socket, BufferedWriter bufferedWriter, BufferedReader bufferedReader){
try{
if(bufferedReader != null){
bufferedReader.close();
}
if(bufferedWriter != null){
bufferedWriter.close();
}
if(socket != null){
socket.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}