-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChatServer.java
246 lines (212 loc) · 9.29 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
package chat;
import com.sun.org.apache.xerces.internal.parsers.CachingParserPool;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
/**
* A multithreaded chat room server. When a client connects the
* server requests a screen name by sending the client the
* text "SUBMITNAME", and keeps requesting a name until
* a unique one is received. After a client submits a unique
* name, the server acknowledges with "NAMEACCEPTED". Then
* all messages from that client will be broadcast to all other
* clients that have submitted a unique screen name. The
* broadcast messages are prefixed with "MESSAGE ".
*
* Because this is just a teaching example to illustrate a simple
* chat server, there are a few features that have been left out.
* Two are very useful and belong in production code:
*
* 1. The protocol should be enhanced so that the client can
* send clean disconnect messages to the server.
*
* 2. The server should do some logging.
*/
public class ChatServer {
/**
* The port that the server listens on.
*/
private static final int PORT = 9001;
/**
* The set of all names of clients in the chat room. Maintained
* so that we can check that new clients are not registering name
* already in use.
*/
private static HashSet<String> names = new HashSet<String>();
/**
* The set of all the print writers for all the clients. This
* set is kept so we can easily broadcast messages.
*/
private static HashSet<PrintWriter> writers = new HashSet<PrintWriter>();
/*
* hash that contains user name with message
*/
private static HashMap<String, PrintWriter> data = new HashMap<String, PrintWriter>();
/**
* The appplication main method, which just listens on a port and
* spawns handler threads.
*/
public static void main(String[] args) throws Exception {
System.out.println("The chat server is running.");
ServerSocket listener = new ServerSocket(PORT);
try {
while (true) {
new Handler(listener.accept()).start();
}
} finally {
listener.close();
}
}
/**
* A handler thread class. Handlers are spawned from the listening
* loop and are responsible for a dealing with a single client
* and broadcasting its messages.
*/
private static class Handler extends Thread {
private String name;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
/**
* Constructs a handler thread, squirreling away the socket.
* All the interesting work is done in the run method.
*/
public Handler(Socket socket) {
this.socket = socket;
}
/**
* Services this thread's client by repeatedly requesting a
* screen name until a unique one has been submitted, then
* acknowledges the name and registers the output stream for
* the client in a global set, then repeatedly gets inputs and
* broadcasts them.
*/
public void run() {
try {
// Create character streams for the socket.
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
// Request a name from this client. Keep requesting until
// a name is submitted that is not already used. Note that
// checking for the existence of a name and adding the name
// must be done while locking the set of names.
while (true) {
out.println("SUBMITNAME");
name = in.readLine();
if (name == null) {
return;
}
synchronized (names) {
if (!names.contains(name)) {
names.add(name);
break;
}
}
}
// Now that a successful name has been chosen, add the
// socket's print writer to the set of all writers so
// this client can receive broadcast messages.
out.println("NAMEACCEPTED");
writers.add(out);
String clientName = "NAMELIST ";
/*
* Sending the client list to client
*/
for(String n : names){
clientName += n+':';
}
for(PrintWriter pw:writers)
{
System.out.println(writers);
pw.println(clientName);
}
data.put(name, out);
// Accept messages from this client and broadcast them.
// Ignore other clients that cannot be broadcasted to.
while (true) {
String input = in.readLine();
if (input == null) {
return;
}
else if(input.contains(">>")) {
String temp[] = input.split(">>");
PrintWriter receiver = data.get(temp[0]);
receiver.println("MESSAGE " + name + ": " + temp[1]);
out.println("MESSAGE " + name + ": " + temp[1]);
}
else if(input.startsWith("MULTICAST")){
input = input.substring(9);
System.out.println("Multicast working");
System.out.println(input);
/*
* temp1 for split the message
* users tokenizer is used to access the client name one by one with delimeter $
*/
String temp[] = input.split("%");
StringTokenizer users = new StringTokenizer(temp[0], "$");
/*
* sending the message to relevent client
*/
while(users.hasMoreTokens()){
data.get(users.nextToken().trim()).println("MESSAGE " + name + ": " + temp[1]);
}
// for(String receiver : temp2){
// System.out.println(receiver);
// try{
//// System.out.println(receiver);
//// System.out.println(temp[1]);
//// System.out.println(data.get(receiver));
// //data.get(receiver).println("MESSAGE " + name + ": " + temp[1]);
// }
// catch(Exception e){
// e.printStackTrace();
// }
// }
// data.get(temp[0]).println("MESSAGE " + name + ": " + temp[1]);
out.println("MESSAGE " + name + ": " + temp[1]);
System.out.println("sender");
}
else if(input.startsWith("BROADCAST"))
{
for (PrintWriter writer : writers) {
writer.println("MESSAGE " + name + ": " + input.substring(9));
}
}
}
} catch (IOException e) {
System.out.println(e);
} finally {
// This client is going down! Remove its name and its print
// writer from the sets, and close its socket.
if (name != null) {
names.remove(name);
}
if (out != null) {
writers.remove(out);
/*
* Update list after a client exited
*/
String clientName = "NAMELIST ";
for(String n : names){
clientName += n+':';
}
for(PrintWriter pw:writers)
{
pw.println(clientName);
}
}
try {
socket.close();
} catch (IOException e) {
}
}
}
}
}