-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerMasterThread.java
More file actions
365 lines (285 loc) · 11.7 KB
/
ServerMasterThread.java
File metadata and controls
365 lines (285 loc) · 11.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
package unimelb.bitbox;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import unimelb.bitbox.util.HostPort;
//import unimelb.bitbox.util.FileSystemManager;
//import unimelb.bitbox.util.FileSystemObserver;
import unimelb.bitbox.util.FileSystemManager.FileSystemEvent;
//import java.security.NoSuchAlgorithmException;
//import java.util.Queue;
//import java.util.LinkedList;
import java.util.ArrayList;
import java.util.HashMap;
//import java.nio.ByteBuffer;
//import java.nio.charset.Charset;
public class ServerMasterThread extends Thread {
private final String hostS;
private final int portS;
private ServerSocket serverSocket;
private BufferedReader in;
private BufferedWriter out;
private final int maxIncomingConnection;
private ServerMain fileServer;
private ArrayList<String> conClientList;
private HashMap<String, RemotePeerInfo> conClientDic;
private final long maxBlockSize;
public ServerMasterThread(HostPort server, int maxInCon, ServerMain fileServer, long maxBlockSize) {
this.hostS = server.host;
this.portS = server.port;
serverSocket = null;
in = null;
out = null;
maxIncomingConnection = maxInCon;
this.fileServer = fileServer;
//conClientList = new ArrayList<String>();
//conClientDic = new HashMap<String, ClientInfo>();
conClientList = fileServer.inConPeerList;
conClientDic = fileServer.inConPeerDic;
this.maxBlockSize = maxBlockSize;
try {
serverSocket = new ServerSocket(portS);
}
catch (SocketException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
/**@override*/
public void run() {
try {
int countInCon = 0;
while(true) {
// Recycles disconnected server thread and update countInCon
countInCon = updateClientList(countInCon);
// Accepts an incoming client connection request
Socket socketC = serverSocket.accept();
countInCon++;
// input for this request
in = new BufferedReader(new InputStreamReader(socketC.getInputStream(), "UTF-8"));
// Output for this request
out = new BufferedWriter(new OutputStreamWriter(socketC.getOutputStream(), "UTF-8"));
// Receives an client request
String hsReq = in.readLine();
System.out.println("A new incommong client says: " + hsReq);
// Handles "HANDSHAKE_REQUEST"
boolean hsSuccess = hsReqHandler(hsReq, countInCon, socketC);
if(!hsSuccess) {
socketC.close();
countInCon--;
}
in = null;
out = null;
}
}
catch (SocketException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
finally {
if(serverSocket!= null) {
try {
serverSocket.close();
}
catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
}
// Removess disconnected clients and update countInCon
private int updateClientList(int countInCon){
ArrayList<String> disConList = new ArrayList<String>();
try {
for(int i=0; i<conClientList.size(); i++) {
String name = conClientList.get(i);
RemotePeerInfo client = conClientDic.get(name);
//Pitfall: socket.isClosed() will never return true
// unless the local host closes the socket actively
//if(client.socket==null || client.socket.isClosed()) {
if(client.socket==null || !client.socket.getInetAddress().isReachable(3000)) {
if(client.receiver!=null) {
client.receiver.terminate();
}
if(client.transmitter!=null) {
client.transmitter.terminate();
}
disConList.add(name);
conClientDic.remove(name);
System.out.println("Kills client "+name);
countInCon--;
}
else if(client.receiver==null || client.receiver.getState().equals(Thread.State.valueOf("TERMINATED"))) {
if(client.transmitter!=null) {
client.transmitter.terminate();
}
disConList.add(name);
conClientDic.remove(name);
System.out.println("Kills client "+name);
countInCon--;
}
else if(client.transmitter==null || client.transmitter.getState().equals(Thread.State.valueOf("TERMINATED"))) {
if(client.receiver!=null) {
client.receiver.terminate();
}
disConList.add(name);
conClientDic.remove(name);
System.out.println("Kills client "+name);
countInCon--;
}
}
if(conClientList.size()>0 && disConList.size()>0) {
conClientList.removeAll(disConList);
}
// for verification
if(countInCon!=conClientList.size()) {
System.out.println("Warning: bugs in server countInCon");
}
}
catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
System.out.println("Alive clients: "+countInCon);
return countInCon;
}
private boolean hsReqHandler(String hsReq, int countCon, Socket socketC) {
JSONParser parser = new JSONParser();
try {
JSONObject req = (JSONObject) parser.parse(hsReq);
if(!req.containsKey("command")) {
sendInvalid("message must contain a command field as string");
return false;
}
else {
boolean hsStatus;
String command = (String) req.get("command");
switch(command)
{
case "HANDSHAKE_REQUEST":
if(!req.containsKey("hostPort")) {
sendInvalid("HANDSHAKE_REQUEST message must contain a hostPort field");
hsStatus = false;
}
else {
JSONObject hostPort = (JSONObject) req.get("hostPort");
if(!hostPort.containsKey("host") || !hostPort.containsKey("port")) {
sendInvalid("HANDSHAKE_REQUEST message must contain a host or port field");
hsStatus = false;
}
else {
if(countCon > maxIncomingConnection) {
sendConRefuse();
hsStatus = false;
}
else {
System.out.println("From Server: Valid hand shake request!");
String hostC = (String) hostPort.get("host");
int portC = ((Number) hostPort.get("port")).intValue();
TransmitterThread tx = new TransmitterThread(hostC, portC, socketC);
ReceiverThread rx = new ReceiverThread(hostC, portC, socketC, fileServer, maxBlockSize);
// gen sync event
ArrayList<FileSystemEvent> iniSyncEventList = fileServer.fileSystemManager.generateSyncEvents();
tx.fileEventList.addAll(iniSyncEventList);
String clientName = (new HostPort(hostC, portC)).toString();
RemotePeerInfo clientInfo = new RemotePeerInfo(hostC, portC, socketC, tx, rx);
conClientList.add(clientName);
conClientDic.put(clientName, clientInfo);
sendHSRes();
tx.start();
rx.start();
hsStatus = true;
}
}
}
break;
default:
sendInvalid("invalid HANDSHAKE_REQUEST");
hsStatus = false;
break;
}
return hsStatus;
}
}
catch (ParseException e){
sendInvalid("server parsing failure");
return false;
}
catch (ClassCastException e){
sendInvalid("server parsing failure");
return false;
}
}
private void sendHSRes() {
try {
JSONObject hostPortS = new JSONObject();
hostPortS.put("host", hostS);
hostPortS.put("port", portS);
JSONObject hsRes = new JSONObject();
hsRes.put("command", "HANDSHAKE_RESPONSE");
hsRes.put("hostPort", hostPortS);
out.write(hsRes.toJSONString() +"\n");
out.flush();
System.out.println(hsRes.toJSONString());
}
catch(IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
private void sendConRefuse() {
try {
JSONArray peers = new JSONArray();
for(int i=0; i<conClientList.size(); i++) {
RemotePeerInfo server = conClientDic.get(conClientList.get(i));
JSONObject peer = new JSONObject();
peer.put("host", server.host);
peer.put("port", server.port);
peers.add(peer);
}
JSONObject conRef = new JSONObject();
conRef.put("command", "CONNECTION_REFUSED");
conRef.put("message", "connection limit reached");
conRef.put("peers", peers);
out.write(conRef.toJSONString() +"\n");
out.flush();
System.out.println(conRef.toJSONString());
}
catch(IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
private void sendInvalid(String msg) {
try {
JSONObject invalidPro = new JSONObject();
invalidPro.put("command", "INVALID_PROTOCOL");
invalidPro.put("message", msg);
out.write(invalidPro.toJSONString() +"\n");
out.flush();
System.out.println(invalidPro.toJSONString());
}
catch(IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}