My favorites | Sign in
Project Home Wiki Issues Source
READ-ONLY: This project has been archived. For more information see this post.
Search
for
  Advanced search   Search tips   Subscriptions

Issue 10 attachment: Server.java (13.7 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
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
/**
* ChatServer - Server class
* @author Waterlgndx
* 05/20/2012
* Server is a class that hosts the chat. I admit it is probably a bit messy. I also find it strange that I
* ended up using an Array of ThreadHandlers instead of a hash of some sort. I would like to use a hash for
* commands or command aliases I would like to add ServerObjects which users would be able to interact with
* and set behavior/properties via the command aliases developed. But this may be much further down the road.
*
* classes: Server, ThreadHandler
*/


package net.dreamersnet.ChatServer;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Date;

/**
* ThreadHandler : a class that handles threads for the sockets for connected user. These threads handle
* incoming and outgoing messages with regards to the users connected.
* @author Ben Parker
*/
class ThreadHandler extends Thread {
Socket socket;
Server serv;
String userName = new String(" ");
String message = new String (" ");
boolean terminated = false;
int n; //Thread Number

ThreadHandler(Server serv, Socket s, int v) {
this.serv = serv;
socket = s;
n= v;
}

//TODO: Change so that the Server side completely manages the user name after connection...
public void run()
{
try {
// prime the loop and get user name and get client added to the server...
//Read incoming message. In future versions it will not be important
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//PrintWriter printWriter = new PrintWriter(socket.getOutputStream(),true);
message = bufferedReader.readLine();
if ((message.indexOf("!#@") >= 0) && (message.indexOf("!#@") < 4)) {
String[] tmp = message.split("!#@",2);
message = tmp[1];
String[] tmp2 = message.split(" ",2);
userName = tmp2[0];
message = tmp2[1];
serv.sendCommand(userName, message);
} else {
String[] tmp = message.split(" ",2);
userName = tmp[0];
message = tmp[1];
if (message.length() > 0)
{
System.out.println("<" + userName + "> " + message);
//Respond to client echoing back the incoming client message
serv.sendToAll(this, message);
}
}

//add me
serv.addMe(this);


// continue execution as normal...
while (!terminated) {
//Read incoming message. In future versions it will not be important
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//PrintWriter printWriter = new PrintWriter(socket.getOutputStream(),true);
message = bufferedReader.readLine();
if ((message.indexOf("!#@") >= 0) && (message.indexOf("!#@") < 4)) {
String[] tmp = message.split("!#@",2);
message = tmp[1];
String[] tmp2 = message.split(" ",2);
userName = tmp2[0];
message = tmp2[1];
serv.sendCommand(userName, message);
} else {
String[] tmp = message.split(" ",2);
userName = tmp[0];
message = tmp[1];
if (message.length() > 0)
{
System.out.println("<" + userName + "> " + message);
//Respond to client echoing back the incoming client message
serv.sendToAll(this, message);
}
}
}
} catch (IOException e) {
Date d = new Date();
System.out.println(d.getTime() + ">> ThreadHandler exception occured : " + e);
e.printStackTrace();
System.out.println("Closing socket");
try {
socket.close();
terminated = true;

} catch (Exception e2) {
System.out.println("Close socket failed" + e);
}
return;
}
}

public Socket getSocket()
{
return socket;
}

public void setSocket(Socket s) {
socket = s;
}

public synchronized void sendMessage(String from, String msg)
{
if (terminated) return;
try {
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(),true);
if (msg.length() > 0) {
printWriter.println("<" + from + "> " + msg);
printWriter.flush();
}
} catch (IOException e) {
System.out.println("Message not sent, exception : " + e);
System.out.println("Closing socket and attempting recovery");
try {
serv.sendRawToAll(userName + " had their connection reset! ");
socket.close();
serv.removeThread(this);
terminated = true;
} catch (Exception e2) {
System.out.println("Close socket failed" + e);
}
return;
}
}

//TODO: boolean setSocket() if host names match.

public void setUserName(String newUserName)
{
this.userName = newUserName;
sendRaw("@#!set name " + this.userName);
}

/**
* Deprecated
* @return message
* this will be removed in next update because of its unreliability.
*/
public String getMessage()
{
return message;
}

public String getUserName()
{
return userName;
}

public void sendRaw(String raw)
{
if (terminated) return;
try {
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(),true);
if (raw.length() > 0) {
printWriter.println(raw);
printWriter.flush();
}
} catch (IOException e) {
System.out.println("Raw not sent, exception : " + e);
System.out.println("Closing socket and attempting recovery");
try {
socket.close();
serv.removeThread(this);
terminated = true;
} catch (Exception e2) {
System.out.println("Close socket failed: " + e);
}
return;
}
}

public boolean isClosed()
{
return socket.isClosed();
}

public void terminate()
{
terminated = true;
try {
socket.close();
} catch ( Exception e) {
System.out.println("Error terminating socket for " + userName + ": "+ e);
}
}

}

public class Server {
static ArrayList<ThreadHandler> threads = new ArrayList<ThreadHandler>();
static ArrayList<ThreadHandler> noCXNt = new ArrayList<ThreadHandler>(); //non connected threads
static Server serv = new Server();

public static void main(String[] args) {
int nreq = 1;
try {
ServerSocket serverSocket = new ServerSocket(4444);
for (;;) {
Socket socket = serverSocket.accept();
Thread t = new ThreadHandler(serv, socket, ++nreq);
t.start();
noCXNt.add((ThreadHandler) t);
}
} catch (IOException e) {
System.out.println("exception occured : " + e);
System.exit(-1);
}
}

public synchronized void addMe(Thread t) {
ArrayList<Thread> toRemove = new ArrayList<Thread>();
ThreadHandler tempHandle = (ThreadHandler) t;
String attemptName = tempHandle.getUserName();
for (int i=0; i<threads.size(); i++) {
if (threads.get(i).isClosed()) {
toRemove.add(threads.get(i));
continue;
}
if (threads.get(i).getUserName().compareToIgnoreCase(attemptName)==0) {
System.out.println(attemptName + " is currently in use.");
//match found terminate session with reason.
if (threads.get(i).getSocket().getInetAddress().toString().compareToIgnoreCase(tempHandle.getSocket().getInetAddress().toString())==0) {
// if addresses match replace old session
tempHandle.sendMessage("SERVER", "This name is in use, but your host matches, replacing session.");
threads.get(i).sendMessage("SERVER", "We believe you have been a ghosted user, killing your session.");
threads.get(i).setSocket(tempHandle.getSocket());
tempHandle.terminate();
System.out.println("Username "+ attemptName + " is a duplicated nickname from host: "+ tempHandle.getSocket().getInetAddress().getHostName());
System.out.println("Server detected the host to be a match from it's previous connection so has replaced the connection with the current one");
noCXNt.remove(tempHandle);
return;
} else {
tempHandle.sendMessage("SERVER", "This name is in use!!! You will be disconnected!!");
tempHandle.sendMessage("SERVER", "This name is in use!!! You will be disconnected!!");
//TODO: change it so client is given a chance to change their name
// or if hosts match replace the old connection with the new one.
// with setSocket.
tempHandle.terminate();
System.out.println("Username "+ attemptName + " is a duplicated nickname from host: "+ tempHandle.getSocket().getInetAddress().getHostName());
System.out.println("Original host is " + threads.get(i).getSocket().getInetAddress().getHostName());
noCXNt.remove(tempHandle);
return;
}
}
}
threads.add(tempHandle);
noCXNt.remove(tempHandle);
tempHandle.sendMessage("SERVER", "Welcome to home.dreamersnet.net!");
tempHandle.sendMessage("SERVER", "This is an experiemental chat server!");
for (int i=0; i<toRemove.size();i++)
removeThread(toRemove.get(i));
tempHandle.sendMessage("SERVER", "Just added : /msg and /me commands");
tempHandle.sendMessage("SERVER", "If you see a name with [PM] that indicates it is a private message");

//String userName = ((ThreadHandler) t).getUserName();
}

public synchronized void sendToAll(Thread t, String msg)
{
String userName = ((ThreadHandler) t).getUserName();
//send same message to everyone
if (msg.length() > 0) {
for (int i=0; i<threads.size(); i++) {
if (threads.get(i).isClosed())
continue;
threads.get(i).sendMessage(userName, msg);
}
}
}

public synchronized void sendToAll(String from, String msg)
{
for (int i=0; i<threads.size(); i++) {
if (threads.get(i).isClosed())
continue;
threads.get(i).sendMessage(from, msg);
}

}

public synchronized void sendRawToAll(String raw)
{
for (int i=0; i<threads.size(); i++) {
if (threads.get(i).isClosed())
continue;
threads.get(i).sendRaw(raw);
}
}

public synchronized void removeThread(Thread t)
{
threads.remove(t);
}

private synchronized void sendNamesTo(String from) {
String toSend = "";
int nameCt = 0;
int memory = -1;
for (int i=0; i<threads.size(); i++) {
if (threads.get(i).isClosed())
continue;
if (threads.get(i).getUserName().compareToIgnoreCase(from)==0)
memory = i;
toSend += " " + threads.get(i).getUserName();
nameCt++;
}
if (memory!=-1)
threads.get(memory).sendRaw("* There are "+ nameCt +" users logged in : " + toSend);
}

public synchronized void sendCommand(String from, String command)
{
// Make sure to return after performing the actions required for your command!

// NAMES, WHO command are currently the same thing
if ((command.compareToIgnoreCase("names")== 0) || (command.compareToIgnoreCase("who")==0)) {
sendNamesTo(from);
return;
}
// QUIT command
if (command.compareToIgnoreCase("quit")==0) {
int userThread = -1;
for (int i=0; i<threads.size(); i++)
{
if (threads.get(i).getUserName().compareToIgnoreCase(from)==0)
userThread = i;
}
if ( userThread >= 0 ) {
sendRawToAll("*** Client exiting : " + from);
threads.get(userThread).terminate();
threads.remove(userThread);
}
return;
}
//Multiple parameter commands:
String[] words = command.split(" ", 3);

// QUIT with parameters
if (words[0].compareToIgnoreCase("quit")==0) {
int userThread = -1;
for (int i=0; i<threads.size(); i++)
{
if (threads.get(i).getUserName().compareToIgnoreCase(from)==0)
userThread = i;
}
if ( userThread >= 0 ) {
sendRawToAll("*** Client exiting : " + from + " with reason : " + words[1] + " " + words[2]);
threads.get(userThread).terminate();
threads.remove(userThread);
}
return;
}
// NICK, NICKNAME command
if ((words[0].compareToIgnoreCase("nickname")==0)||(words[0].compareToIgnoreCase("nick")==0)) {
boolean newNickOk = true;
int userThread = -1;
for (int i=0; i<threads.size(); i++)
{
if (threads.get(i).isClosed())
continue;
if (threads.get(i).getUserName().compareToIgnoreCase(words[1])==0) {
newNickOk = false;
}
else if (threads.get(i).getUserName().compareToIgnoreCase(from)==0)
userThread = i;
}
if ((newNickOk) && (userThread >= 0)) {
//change nick and let everyone know
threads.get(userThread).setUserName(words[1]);
sendRawToAll("*** "+ from + " is now known as " + words[1]);
} else {
threads.get(userThread).sendRaw("Nickname changed failed! It appears it is already in use!");
}
return;
}
// MSG , TELL commands (many of my friends are ex-mmo players, adding these for ease)
else if ((words[0].compareToIgnoreCase("msg")== 0) || (words[0].compareToIgnoreCase("tell")== 0)) {
boolean sent = false;
int fromUser = -1;
for (int i=0; i<threads.size(); i++) {
if (threads.get(i).isClosed())
continue;
if (threads.get(i).getUserName().compareToIgnoreCase(words[1])==0) {
threads.get(i).sendMessage("[PM] "+ from, words[2]);
sent = true;
}
if (threads.get(i).getUserName().compareToIgnoreCase(from)==0)
fromUser = i;
} //end for loop
if ((fromUser >= 0) && sent) {
threads.get(fromUser).sendMessage("Sent PM["+ words[1] + "]", ": " + words[2]);
}
return;
}
// ME , EMOTE commands
else if ((words[0].compareToIgnoreCase("me")== 0) || (words[0].compareToIgnoreCase("emote")== 0)) {
String tmp="";
for (int i=1; i<words.length; i++)
tmp += words[i] + " ";
sendRawToAll("ACTION: * " + from + " "+ tmp.trim());
}
else {
try {
System.out.println("Unknown command raw: " + command);
System.out.println("words[0]:" + words[0]);
System.out.println("words[1]:" + words[1]);
System.out.println("words[2]:" + words[2]);
} catch (Exception e) {
System.out.println("server sendCommand exception: " + e);
}
}
}
}
Powered by Google Project Hosting