-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.java
More file actions
100 lines (90 loc) · 1.94 KB
/
Copy pathServer.java
File metadata and controls
100 lines (90 loc) · 1.94 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
import java.io.IOException;
import java.io.InvalidObjectException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
public class Server
{
private HashMap<String, Socket> map;
private HashMap<String, Integer> count;
private ServerSocket ss = null;
private int mode = -1;
Server(int port, int mode) throws InvalidObjectException
{
map = new HashMap<>();
count = new HashMap<>();
this.mode = mode;
try
{
ss = new ServerSocket(port);
}
catch (IOException e)
{
// e.printStackTrace();
throw new InvalidObjectException("PORT_ERROR");
}
}
private void start()
{
while(true)
{
try
{
Socket s = ss.accept();
new Thread(new ServerThread(s, this, mode)).start();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public synchronized void insert(String s, Socket sock)
{
map.put(s, sock);
}
public synchronized Socket get(String s)
{
return map.get(s);
}
//If receiver thread is run first then map fails
public synchronized boolean contains(String s)
{
if(!map.containsKey(s))
return false;
if(!count.containsKey(s))
return false;
return count.get(s)>=2;
}
//If receiver thread is run first
public synchronized void updateCount(String s)
{
if(count.containsKey(s))
count.put(s, new Integer(count.get(s)+1));
else
count.put(s,1);
}
public synchronized void delete(String s)
{
if(map.containsKey(s))
map.remove(s);
if(count.containsKey(s))
count.remove(s);
}
public static void main(String[] args)
{
try
{
new Server(Integer.parseInt(args[0]), Integer.parseInt(args[1])).start();
}
catch (InvalidObjectException e)
{
System.out.println("Port occupied or permission denied");
}
catch(Exception e)
{
System.out.println("Please enter valid parameters");
}
}
}