forked from DomHeal/JavaFX-Chat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.java
More file actions
230 lines (208 loc) · 8.19 KB
/
Server.java
File metadata and controls
230 lines (208 loc) · 8.19 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
package com.server;
import com.exception.DuplicateUsernameException;
import com.messages.Message;
import com.messages.MessageType;
import com.messages.Status;
import com.messages.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
public class Server {
/* Setting up variables */
private static final int PORT = 9001;
private static final HashMap<String, User> names = new HashMap<>();
private static HashSet<ObjectOutputStream> writers = new HashSet<>();
private static ArrayList<User> users = new ArrayList<>();
static Logger logger = LoggerFactory.getLogger(Server.class);
public static void main(String[] args) throws Exception {
logger.info("The chat server is running.");
ServerSocket listener = new ServerSocket(PORT);
try {
while (true) {
new Handler(listener.accept()).start();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
listener.close();
}
}
private static class Handler extends Thread {
private String name;
private Socket socket;
private Logger logger = LoggerFactory.getLogger(Handler.class);
private User user;
private ObjectInputStream input;
private OutputStream os;
private ObjectOutputStream output;
private InputStream is;
public Handler(Socket socket) throws IOException {
this.socket = socket;
}
public void run() {
logger.info("Attempting to connect a user...");
try {
is = socket.getInputStream();
input = new ObjectInputStream(is);
os = socket.getOutputStream();
output = new ObjectOutputStream(os);
Message firstMessage = (Message) input.readObject();
checkDuplicateUsername(firstMessage);
writers.add(output);
sendNotification(firstMessage);
addToList();
while (socket.isConnected()) {
Message inputmsg = (Message) input.readObject();
if (inputmsg != null) {
logger.info(inputmsg.getType() + " - " + inputmsg.getName() + ": " + inputmsg.getMsg());
switch (inputmsg.getType()) {
case USER:
write(inputmsg);
break;
case VOICE:
write(inputmsg);
break;
case CONNECTED:
addToList();
break;
case STATUS:
changeStatus(inputmsg);
break;
}
}
}
} catch (SocketException socketException) {
logger.error("Socket Exception for user " + name);
} catch (DuplicateUsernameException duplicateException){
logger.error("Duplicate Username : " + name);
} catch (Exception e){
logger.error("Exception in run() method for user: " + name, e);
} finally {
closeConnections();
}
}
private Message changeStatus(Message inputmsg) throws IOException {
logger.debug(inputmsg.getName() + " has changed status to " + inputmsg.getStatus());
Message msg = new Message();
msg.setName(user.getName());
msg.setType(MessageType.STATUS);
msg.setMsg("");
User userObj = names.get(name);
userObj.setStatus(inputmsg.getStatus());
write(msg);
return msg;
}
private synchronized void checkDuplicateUsername(Message firstMessage) throws DuplicateUsernameException {
logger.info(firstMessage.getName() + " is trying to connect");
if (!names.containsKey(firstMessage.getName())) {
this.name = firstMessage.getName();
user = new User();
user.setName(firstMessage.getName());
user.setStatus(Status.ONLINE);
user.setPicture(firstMessage.getPicture());
users.add(user);
names.put(name, user);
logger.info(name + " has been added to the list");
} else {
logger.error(firstMessage.getName() + " is already connected");
throw new DuplicateUsernameException(firstMessage.getName() + " is already connected");
}
}
private Message sendNotification(Message firstMessage) throws IOException {
Message msg = new Message();
msg.setMsg("has joined the chat.");
msg.setType(MessageType.NOTIFICATION);
msg.setName(firstMessage.getName());
msg.setPicture(firstMessage.getPicture());
write(msg);
return msg;
}
private Message removeFromList() throws IOException {
logger.debug("removeFromList() method Enter");
Message msg = new Message();
msg.setMsg("has left the chat.");
msg.setType(MessageType.DISCONNECTED);
msg.setName("SERVER");
msg.setUserlist(names);
write(msg);
logger.debug("removeFromList() method Exit");
return msg;
}
/*
* For displaying that a user has joined the server
*/
private Message addToList() throws IOException {
Message msg = new Message();
msg.setMsg("Welcome, You have now joined the server! Enjoy chatting!");
msg.setType(MessageType.CONNECTED);
msg.setName("SERVER");
write(msg);
return msg;
}
/*
* Creates and sends a Message type to the listeners.
*/
private void write(Message msg) throws IOException {
for (ObjectOutputStream writer : writers) {
msg.setUserlist(names);
msg.setUsers(users);
msg.setOnlineCount(names.size());
writer.writeObject(msg);
writer.reset();
}
}
/*
* Once a user has been disconnected, we close the open connections and remove the writers
*/
private synchronized void closeConnections() {
logger.debug("closeConnections() method Enter");
logger.info("HashMap names:" + names.size() + " writers:" + writers.size() + " usersList size:" + users.size());
if (name != null) {
names.remove(name);
logger.info("User: " + name + " has been removed!");
}
if (user != null){
users.remove(user);
logger.info("User object: " + user + " has been removed!");
}
if (output != null){
writers.remove(output);
logger.info("Writer object: " + user + " has been removed!");
}
if (is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (input != null){
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
removeFromList();
} catch (Exception e) {
e.printStackTrace();
}
logger.info("HashMap names:" + names.size() + " writers:" + writers.size() + " usersList size:" + users.size());
logger.debug("closeConnections() method Exit");
}
}
}