-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathChatServer.java
419 lines (379 loc) · 14.1 KB
/
ChatServer.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
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.ServerSocket;
import java.util.*;
import java.text.SimpleDateFormat;
/**
* A chat server that delivers public and private messages.
*/
public class ChatServer {
// The server socket.
private static ServerSocket serverSocket = null;
// The client socket.
private static Socket clientSocket = null;
//An ArrayList to keep list of clients
private static ArrayList<ClientThread> clients;
// to display time
private static SimpleDateFormat sdf;
public static void main(String args[]) {
clients = new ArrayList<>();
// to display hh:mm:ss
sdf = new SimpleDateFormat("HH:mm:ss");
// The default port number.
int portNumber = 5000 ;
switch(args.length)
{
case 0: {
System.out.println("Usage: java ChatServer <portNumber>\n"
+ "By default using port number=" + portNumber);
break;
}
case 1: {
try
{
portNumber = Integer.parseInt(args[0]);
break;
}
catch(Exception e)
{
System.out.println("Invalid port number.");
System.out.println("Usage is: > java Server [portNumber]");
return;
}
}
default:{
System.out.println("Usage: java ChatServer <portNumber>");
return;
}
}
/*
* Open a server socket on the portNumber (default 5000). Note that we can
* not choose a port less than 1023 if we are not privileged users (root).
*/
try
{
serverSocket = new ServerSocket(portNumber);
}
catch (IOException e)
{
String msg = sdf.format(new Date()) + " Exception on new ServerSocket: " + e + "\n";
display(msg);
}
/*
* Create a client socket for each connection and pass it to a new client
* thread.
*/
boolean ContinueRunningServer = true;
while (ContinueRunningServer)
{
try
{
display("Server waiting for Clients on port " + portNumber + ".");
clientSocket = serverSocket.accept();
// break if server stoped
if(!ContinueRunningServer)
break;
// if client is connected, create its thread
ClientThread t = new ClientThread(clientSocket, clients);
//add this client to arraylist
clients.add(t);
t.start();
}
catch (IOException e)
{
String msg = sdf.format(new Date()) + " Exception on new ServerSocket: " + e + "\n";
display(msg);
}
}
// try to stop the server
try
{
serverSocket.close();
for(ClientThread tc : clients)
{
try
{
tc.CloseAll();
}
catch(Exception e)
{
display("Exception closing " + e);
}
}
}
catch(Exception e)
{
display("Exception closing the server and clients: " + e);
}
}
// Display a message on console
private static void display(String msg){
String time = sdf.format(new Date()) + " " + msg;
System.out.println(time);
}
}
/*
* The chat client thread. This client thread opens the input and the output
* streams for a particular client, ask the client's name, informs all the
* clients connected to the server about the fact that a new client has joined
* the chat room, and as long as it receive data, echos that data back to all
* other clients. The thread broadcast the incoming messages to all clients and
* routes the private message to the particular client. When a client leaves the
* chat room this thread informs also all the clients about that and terminates.
*/
class ClientThread extends Thread {
private String clientName = null;
private ObjectInputStream is = null;
private ObjectOutputStream os = null;
private Socket clientSocket = null;
private final ArrayList<ClientThread> threads;
// timestamp
String date;
// message object to recieve message and its type
Message msg;
// to display time
private SimpleDateFormat sdf;
public ClientThread(Socket clientSocket,ArrayList<ClientThread> threads) {
this.clientSocket = clientSocket;
this.threads = threads;
sdf = new SimpleDateFormat("HH:mm:ss");
/*
* Create input and output streams for this client.
*/
try
{
is = new ObjectInputStream(clientSocket.getInputStream());
os = new ObjectOutputStream(clientSocket.getOutputStream());
}
catch (IOException e)
{
display("Exception creating new Input/output Streams: " + e);
return;
}
date = new Date().toString();
}
// Display a message on console
private void display(String msg){
String time = sdf.format(new Date()) + " " + msg;
System.out.println(time);
}
//Close everything
public void CloseAll()
{
try
{
if(is != null) is.close();
if(os != null) os.close();
if(clientSocket != null) clientSocket.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
public String GetClientName()
{
return clientName;
}
public void run() {
ArrayList<ClientThread> threads = this.threads;
try
{
String name = "";
boolean nameCheckFailed=true;
while (nameCheckFailed)
{
try
{
name = (String) is.readObject();
}
catch (ClassNotFoundException e)
{
}
if (name.indexOf('@') == -1 && name.indexOf(' ') == -1)
{
boolean ClientsWithSameNameExists=false;
for(ClientThread ct: threads)
{
if(ct != this)
{
if(name.equals(ct.GetClientName()))
{
os.writeObject("The name " + name + " is already taken. Please enter a different username.\n");
ClientsWithSameNameExists = true;
break;
}
}
}
nameCheckFailed = ClientsWithSameNameExists;
}
else
{
os.writeObject("The name should not contain '@' character or space. Please enter a different username.\n");
}
}
os.writeObject("OK NAME");
clientName=name;
/* Welcome the new the client. */
os.writeObject("Welcome " + clientName
+ " to our chat room.\nTo leave enter \"signout\" in a new line. To send private method use @user message");
broadcast(" *** A new user " + clientName + " has joined the chat room." + " *** ");
/* Start the conversation. */
boolean ContinueConversation=true;
while (ContinueConversation)
{
try
{
msg = (Message) is.readObject();
}
catch (IOException e)
{
display(clientName + " Exception reading Streams: " + e);
break;
}
catch (ClassNotFoundException e)
{
}
// get the message from the Message object received
String message = msg.getMessage();
// different actions based on type message
// different actions based on type message
switch(msg.getType()) {
case MESSAGE:
boolean confirmation = broadcast(clientName + ": " + message);
if(confirmation==false){
String msg = " *** " + "Sorry. No such user exists." + " *** ";
os.writeObject(msg);
}
break;
case SIGNOUT:
display(clientName + " disconnected with a SIGNOUT message.");
ContinueConversation = false;
os.writeObject("*** Bye " + clientName + " ***");
break;
case GETUSERS:
os.writeObject("List of the users connected at " + sdf.format(new Date()) + "\n");
// send list of active clients
for(ClientThread ct : threads)
{
if((ct != this) && (ct.GetClientName() != null))
{
os.writeObject(" @@@ " + ct.GetClientName() + " since " + ct.date + "\n");
}
}
break;
}
}
broadcast(" *** User " + clientName + " is leaving the chat room." + " *** ");
/*
* Clean up. Set the current thread variable to null so that a new client
* could be accepted by the server.
*/
threads.remove(this);
/*
* Close the output stream, close the input stream, close the socket.
*/
CloseAll();
} catch (IOException e) {
}
}
// to broadcast a message to all Clients
private synchronized boolean broadcast(String message) {
// add timestamp to the message
String time = sdf.format(new Date());
// to check if message is private i.e. client to client message
String[] w = message.split(" ",3);
boolean isPrivate = false;
if(w[1].charAt(0)=='@')
isPrivate=true;
// if private message, send message to mentioned username only
if(isPrivate==true)
{
String tocheck=w[1].substring(1, w[1].length());
message=w[0]+w[2];
String messageLf = time + " (Private Message) " + message + "\n";
boolean found=false;
// we loop in reverse order to find the mentioned username
for(int y=threads.size(); --y>=0;)
{
ClientThread ct1=threads.get(y);
String check=ct1.GetClientName();
if(check != null && check.equals(tocheck))
{
// try to write to the Client if it fails remove it from the list
if(!ct1.writeMsg(messageLf)) {
threads.remove(y);
display("Disconnected Client " + ct1.GetClientName() + " removed from list.");
}
// username found and delivered the message
found=true;
// display message
System.out.print(messageLf);
break;
}
}
// mentioned user not found, return false
if(found!=true)
{
return false;
}
}
// if message is a broadcast message
else
{
String messageLf = time + " " + message + "\n";
// display message
System.out.print(messageLf);
// we loop in reverse order in case we would have to remove a Client
// because it has disconnected
for(int i = threads.size(); --i >= 0;) {
ClientThread ct = threads.get(i);
// try to write to the Client if it fails remove it from the list
if(ct.GetClientName() != null)
{
if(!ct.writeMsg(messageLf))
{
threads.remove(i);
display("Disconnected Client " + ct.GetClientName() + " removed from list.");
}
}
}
}
return true;
}
// write a String to the Client output stream
private boolean writeMsg(String msg) {
// if Client is still connected send the message to it
if(!clientSocket.isConnected()) {
CloseAll();
return false;
}
// write the message to the stream
try {
os.writeObject(msg);
}
// if an error occurs, do not abort just inform the user
catch(IOException e) {
display(" *** " + "Error sending message to " + clientName + " *** ");
display(e.toString());
}
return true;
}
// if client sent SIGNOUT message to exit
synchronized void remove(int id) {
String disconnectedClient = "";
// scan the array list until we found the Id
for(int i = 0; i < threads.size(); ++i) {
ClientThread ct = threads.get(i);
// if found remove it
if(ct.GetClientName().equals(GetClientName())) {
disconnectedClient = ct.GetClientName();
threads.remove(i);
break;
}
}
broadcast(" *** " + disconnectedClient + " has left the chat room." + " *** ");
}
}