-
Notifications
You must be signed in to change notification settings - Fork 1
/
BootStrap_Server.java
103 lines (87 loc) · 2.57 KB
/
BootStrap_Server.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
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;
@SuppressWarnings("serial")
public class BootStrap_Server implements Runnable,Serializable {
static CopyOnWriteArrayList<InetAddress> IpTable;
Socket s;
Thread t;
static {
IpTable=new CopyOnWriteArrayList<InetAddress>();
}
public BootStrap_Server(Socket s) {
this.s = s;
t=new Thread(this);
t.start();
}
void addNewNode(InetAddress ip) {
BootStrap_Server.IpTable.add(ip);
}
InetAddress lookUp() {
if (BootStrap_Server.IpTable.isEmpty())
return null;
else {
Random rand = new Random();
return IpTable.get(rand.nextInt(BootStrap_Server.IpTable.size()));
}
}
void printIPTable() {
for(InetAddress I:IpTable) {
System.out.println(I.getHostName()+" "+I.getHostAddress());
}
}
public void run() {
synchronized (BootStrap_Server.IpTable) {
try {
ObjectInputStream in=new ObjectInputStream(s.getInputStream());
Object receivedObject=in.readObject();
if(receivedObject instanceof REQUEST_ENTRY_BOOTSTRAP) {
REQUEST_ENTRY_BOOTSTRAP reb=(REQUEST_ENTRY_BOOTSTRAP) receivedObject;
System.out.println("Node Joining: " + reb.joiningIP.getHostName());
ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
InetAddress dest = reb.joiningIP;
out.writeObject(this.lookUp());
this.addNewNode(dest);
out.close();
printIPTable();
System.out.println();
}
else if(receivedObject instanceof REMOVE_BOOTSTRAP_ENTRY_REQUEST) {
REMOVE_BOOTSTRAP_ENTRY_REQUEST rbe=(REMOVE_BOOTSTRAP_ENTRY_REQUEST) receivedObject;
System.out.println("Node leaving:" + rbe.leavingIP.getHostName());
for(InetAddress ip:IpTable) {
if(ip.equals(rbe.leavingIP))
IpTable.remove(ip);
}
printIPTable();
System.out.println();
}
else {
System.out.println("Unable to classify the request");
}
in.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
@SuppressWarnings("resource")
ServerSocket ss = new ServerSocket(20000);
System.out.println("Server running");
while (true) {
new BootStrap_Server(ss.accept());
//System.out.println("client trying to access BootStrap server");
}
}
}