-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClientHandler.java
More file actions
201 lines (181 loc) · 6.99 KB
/
ClientHandler.java
File metadata and controls
201 lines (181 loc) · 6.99 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
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
/**
* @auther Yongchang He
* @profile StuID:11279620 yoh534@usask.ca
* @date 2021-10-09 12:01 p.m.
* @project Assignment1_Chatroom
* @discription When socket is connected, clientHandlers will receive message from clients
* , and forward message to aimed clients.
**/
/**
* This class is simple, just to convey the current directory to other class
* Your first thing is to substitute my directory with your current directory.
*/
class CurrentDir {
// REMINDER!!
// need first to substitute dir with your own directory for the code
private static final String dir = "/home/yoh534/IdeaProjects/Assignment1_Chatroom/src/";
// constructor
public CurrentDir() {
}
// getter to get dir
public static String getDir() {
return dir + "history.txt";
}
}
public class ClientHandler implements Runnable {
// member variables
private Socket socket;
// define ArrayList to hold clientHandlers
public static ArrayList<ClientHandler> clientHandlers = new ArrayList<>();
private BufferedReader bufferedReader;
private BufferedWriter bufferedWriter;
// member variable clientUsername hold client's name
private String clientUsername;
//convey currentClientNumber from class Server
private Server server;
public Server getServer() {
return server;
}
// getter get client's name;
public String getClientUsername() {
return clientUsername;
}
/**
* Constructor: initialize socket, bufferedWriter, bufferedReader, use readLine()to acquire
* client's name from terminal, and add these above to ArrayList ClientHandler
* Server's terminal will announce a connection when a client input their name and 'enter'
*
* @param socket Socket object
*/
public ClientHandler(Socket socket) {
try {
this.socket = socket;
this.bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
this.bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.clientUsername = bufferedReader.readLine();
clientHandlers.add(this);
broadcastMessage("SERVER: '" + clientUsername + "' has entered the chat!~");
} catch (IOException e) {
closeEverything(socket, bufferedReader, bufferedWriter);
}
}
/**
* When socket is connected, receive message from current client and broadcast
* message to aimed client/clients.
*/
@Override
public void run() {
String messageFromClient;
while (socket.isConnected()) {
try {
messageFromClient = bufferedReader.readLine();
broadcastMessage(messageFromClient);
} catch (IOException e) {
closeEverything(socket, bufferedReader, bufferedWriter);
broadcastMessage("SERVER: '" + clientUsername + "' has left");
// decrease the number of current client
// currently cannot decrease the number of client...
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//server.decCurrentClientNumber();
break;
}
}
}
/**
* If the message received contains "@" in front of a username(with no blank),
* send this message to the related user only; if the message received do not
* contain "@", send message to all clients except the message sender.
*
* @param messageToSend message from client
*/
public void broadcastMessage(String messageToSend) {
currentMsgToFile(messageToSend);
for (ClientHandler clientHandler : clientHandlers) {
try {
if (messageToSend != null) {
if (messageToSend.contains("@")) {
if (!clientHandler.clientUsername.equalsIgnoreCase(clientUsername)) {
if (messageToSend.contains(clientHandler.clientUsername)) {
String newMessageToSend = messageToSend.replaceAll("@" + clientHandler.clientUsername, "");
clientHandler.bufferedWriter.write(newMessageToSend);
clientHandler.bufferedWriter.newLine();
clientHandler.bufferedWriter.flush();
}
}
} else if (!clientHandler.clientUsername.equalsIgnoreCase(clientUsername)) {
clientHandler.bufferedWriter.write(messageToSend);
clientHandler.bufferedWriter.newLine();
clientHandler.bufferedWriter.flush();
// write current message to file
//currentMsgToFile(messageToSend);
}
} else {
closeEverything(socket, bufferedReader, bufferedWriter);
break;
}
} catch (IOException e) {
closeEverything(socket, bufferedReader, bufferedWriter);
}
}
}
/**
* This method write current message sent by connected clients to a file named 'history.txt'.
* and the content will be displayed will new client is connected.
*
* @param messageToSend message that prepared to write into a file.
*/
private void currentMsgToFile(String messageToSend) {
messageToSend = messageToSend + "\n";
FileOutputStream fos = null;
try {
// file to store all message sent by clients
//fos = new FileOutputStream(dir, true);
fos = new FileOutputStream(CurrentDir.getDir(), true);
byte[] bs = (messageToSend).getBytes(StandardCharsets.UTF_8);
if (!(messageToSend.contains("SERVER") | messageToSend.contains("@"))) {
fos.write(bs);
}
fos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//
/**
* Close socket and I/O stream method
*/
private void closeEverything(Socket socket, BufferedReader bufferedReader, BufferedWriter bufferedWriter) {
removeClientHandler();
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (bufferedWriter != null) {
bufferedWriter.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* remove clientHandler from ArrayList clientHandlers
*/
public void removeClientHandler() {
clientHandlers.remove(this);
}
}