-
Notifications
You must be signed in to change notification settings - Fork 0
/
ServerMain.java
381 lines (304 loc) · 11.3 KB
/
ServerMain.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
package assignment7;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class ServerMain {
//keeps track of which clients are involved in which chat
//TODO: migrate client lists to ServerObservable class
HashMap<ServerObservable, ArrayList<ClientObserver>> events = new HashMap<ServerObservable, ArrayList<ClientObserver>>();
ArrayList<ClientObserver> clientList = new ArrayList<ClientObserver>();
ServerObservable chatLobby;
// static MongoClient mongoClient;
Object lock = new Object();
static int clientNum;
int serverNum;
ServerSocket serverSock;
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) {
try {
new ServerMain().setUpNetworking();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Adds the chat to the HashMap
* @param event: the type of chat initiated
* @param client: the client that wants to chat
*/
public void registerObserver(ServerObservable chat, ClientObserver client){
//if chat already exists, just add the people to it
if(events.containsKey(chat)){
events.get(chat).add(client);
client.setChat(chat);
}
updateServerClients(chat);
}
/**
* Remove client from list if they want to leave the chat
* @param chat: the chat they are in
* @param client: the client that wants to leave
*/
public void unregisterObserver(ServerObservable chat, ClientObserver client){
if(events.containsKey(chat)){
int index = events.get(chat).indexOf(client);
// if there are still clients left in the chat
if (!events.get(chat).isEmpty()) {
events.get(chat).remove(index);
}
}
}
/**
* Notify when something changes in the specific chat
* @param chat: the chat that changed
*/
public void notifyObservers(ServerObservable chat, ChatPacket data){
ArrayList<ClientObserver> clients = events.get(chat);
for(int i = 0; i < clients.size(); i++){
clients.get(i).update(data);
}
}
@SuppressWarnings("resource")
private void setUpNetworking() throws Exception {
// initial port for clients to connect
serverNum = 0;
// String addr = "169.254.61.84"; // router: 192.168.184.1
// String addr = "localhost"; //name of the ip address
String addr = "0.0.0.0";
// InetAddress ip = InetAddress.getByName(addr);
// ServerSocket serverSock = new ServerSocket(4242, 10, ip); //60784
serverSock = new ServerSocket();
serverSock.bind(new InetSocketAddress(addr, 4242));
System.out.println(serverSock.getLocalSocketAddress());
// System.out.println(ip.getHostName());
// create lobby for chat
chatLobby = new ServerObservable(serverNum);
ArrayList<ClientObserver> clientsLobby = new ArrayList<ClientObserver>();
events.put(chatLobby, clientsLobby);
// constantly accepts clients and adds to observers list
while (true) {
// assign client to their own socket
Socket clientSocket = serverSock.accept();
ObjectOutputStream obj = new ObjectOutputStream(clientSocket.getOutputStream());
// writes output to socket from server -> client
ClientObserver writer = new ClientObserver(++clientNum, clientSocket, obj, chatLobby);
clientList.add(writer);
// create thread to handle (read) each client's "startChat button press"
Thread t = new Thread(new ChatListHandler(clientSocket, writer));
t.start();
System.out.println("GOT A CONNECTION");
}
}
public void updateServerClients(ServerObservable chat) {
ArrayList<String> clients = new ArrayList<String>();
ChatPacket cmd = new ChatPacket();
System.out.println("CHAT " + chat.toString());
for (int i = 0; i < events.get(chat).size(); i++) {
if (chat == chatLobby) {
cmd.setCommand("updateLobbyClients");
System.out.println(events.get(chat).get(i).getClientName());
clients.add(events.get(chat).get(i).getClientName());
} else if (chat.isPrivate) {
cmd.setCommand("updatePrivateClients");
cmd.setChat(chat.toString());
clients.add(events.get(chat).get(i).getClientName());
} else {
cmd.setCommand("updateGroupClients");
cmd.setChat(chat.toString());
clients.add(events.get(chat).get(i).getClientName());
}
}
if (!clients.isEmpty()) {
cmd.setList(clients);
} else {
if (chat == chatLobby) {
cmd.setCommand("updateLobbyClients");
} else if (chat.isPrivate) {
cmd.setCommand("updatePrivateClients");
} else {
cmd.setCommand("updateGroupClients");
}
cmd.setList(new ArrayList<String>(Arrays.asList("")));
}
System.out.println(events + cmd.getCommand());
if (chat == chatLobby) {
for (ClientObserver w : clientList) {
w.update(cmd);
}
//else update it with clients in the chat
} else {
for (ClientObserver w : events.get(chat)) {
w.update(cmd);
}
}
}
public void updateServerChats() {
ArrayList<String> chats = new ArrayList<String>();
//look through the list of the chats and update the list in the lobby
for (ServerObservable s : events.keySet()) {
if (!s.isPrivate) {
chats.add(s.toString());
}
}
chats.remove(chats.indexOf("Chat 0")); // don't display lobby in lobby chat list
ChatPacket cmd = new ChatPacket();
cmd.setCommand("updateLobbyChats");
cmd.setList(chats);
if (!chats.isEmpty()) {
for (ClientObserver w : events.get(chatLobby)) {
w.update(cmd);
}
}
}
// reads data from client
//TODO: rename class and add more for reading chat, lists, buttons
class ChatListHandler implements Runnable {
private ObjectInputStream objectInput;
private ClientObserver client;
private Socket sock;
public ChatListHandler(Socket clientSocket, ClientObserver client) {
sock = clientSocket;
this.client = client;
try {
objectInput = new ObjectInputStream(sock.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
ChatPacket message;
try {
while ((message = (ChatPacket)objectInput.readObject()) != null) {
System.out.println(message.getCommand());
//if the data is a message being transmitted
if(message.getCommand().equals("sendMessage")){
//determine the nature of the chat
if (!this.client.getChat(message.getChat()).isPrivate) {
message.setCommand("groupChat");
} else {
message.setCommand("privateChat");
}
message.setMessage(client.getClientName() + ":\n " + message.getMessage());
System.out.println(this.client.getChat(message.getChat()));
notifyObservers(this.client.getChat(message.getChat()), message);
System.out.println("GROUP MSG SENT: " + message.getMessage());
} else if (message.getCommand().equals("startChat") && events.get(chatLobby).contains(client)) { // starting new chat
ServerObservable chat = new ServerObservable(++serverNum);
ArrayList<ClientObserver> clients = new ArrayList<ClientObserver>();
events.put(chat, clients);
updateServerChats();
ChatPacket cp = new ChatPacket("createdGroupChat");
cp.setMessage(chat.toString());
client.update(cp);
System.out.println("ADDED CHAT");
} else if (message.getCommand().contains("joinChat") && events.get(chatLobby).contains(client)) { // joining existing chat
ServerObservable chat = null;
//look for the chat in the events HashMap
for (ServerObservable s : events.keySet()) {
if (s.toString().equals(message.getMessage())) {
chat = s;
System.out.println("found chat");
break;
}
}
// client.setChat(chat);
ChatPacket cp = new ChatPacket("joiningGroupChat");
cp.setMessage(message.getMessage());
client.update(cp);
//TODO: take out this line to allow multiple chats for one client
// unregisterObserver(chatLobby, client);
registerObserver(chat, client);
updateServerClients(chatLobby);
} else if(message.getCommand().contains("joinPrivateChat")) { // join existing private chat
boolean chatExists = false;
int chatIndex = 0;
for(int i = 0; i < clientList.size(); i++){
if(clientList.get(i).getClientName().contains(message.getMessage())){
chatExists = true;
chatIndex = i;
break;
}
}
if(chatExists){
ChatPacket cm = new ChatPacket("joiningPrivateChat");
ArrayList<ClientObserver> clients = new ArrayList<ClientObserver>();
ServerObservable chat = new ServerObservable(++serverNum);
chat.setPrivate();
cm.setChat(chat.toString());
cm.setMessage(message.getMessage());
this.client.update(cm);
cm.setMessage(this.client.getClientName());
clientList.get(chatIndex).update(cm);
clients.add(this.client);
clients.add(clientList.get(chatIndex));
clientList.get(chatIndex).setChat(chat);
client.setChat(chat);
events.put(chat, clients);
updateServerClients(chat);
}
//TODO: Exit Chat - updateServerClients
}else if(message.getCommand().equals("exitChat")){
//close socket if it is a lobby
if(message.getMessage().equals("Chat 0")){
ArrayList<ServerObservable> chatList = this.client.getChatList();
for(int i = 0; i < chatList.size(); i++){
unregisterObserver(chatList.get(i),this.client);
updateServerClients(chatList.get(i));
}
int index = clientList.indexOf(this.client);
clientList.remove(index);
ChatPacket cp = new ChatPacket("exitedLobby");
this.client.update(cp);
sock.close();
System.out.println("Asdfasdfsa");
if (client.getClientNum() == 1) {
serverSock.close(); // if Client 1 leaves, close server
} else {
Thread.currentThread().stop();
}
} else {
ServerObservable chat = this.client.getChat(message.getMessage());
unregisterObserver(this.client.getChat(message.getMessage()), this.client);
updateServerClients(chat);
}
} else if (message.getCommand().equals("exitPrivateChat")) {
boolean clientExists = false;
int clientIndex = 0;
for(int i = 0; i < clientList.size(); i++){
if(clientList.get(i).toString().contains(message.getMessage())){
clientExists = true;
clientIndex = i;
break;
}
}
if (clientExists) {
System.out.println(clientList.get(clientIndex).toString());
ChatPacket cp = new ChatPacket("exitedPrivateChat");
cp.setMessage(client.toString());
clientList.get(clientIndex).update(cp);
}
} else if (message.getCommand().equals("initMessage")) {
System.out.println("here" + message.getMessage());
client.setClientName(message.getMessage());
registerObserver(chatLobby, client);
updateServerChats();
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}