-
Notifications
You must be signed in to change notification settings - Fork 0
/
SocketServer.java
81 lines (80 loc) · 1.67 KB
/
SocketServer.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
import java.util.*;
import java.io.*;
import java.net.*;
import java.util.concurrent.*;
public class SocketServer {
private GenLL<Socket> connections;
private Thread connectionThread;
private ServerSocket socket;
private QueueInterface<String> msgQ;
public static final int PORT = 5280;
public static final int MAX_USERS = 1;
public static final int MAX_Q_SIZE = 10;
public static final Semaphore MUTEX = new Semaphore(MAX_USERS);
public SocketServer()
{
init();
}
public void init()
{
try
{
connections = new GenLL<Socket>();
msgQ = new LLQueue<String>();
socket = new ServerSocket(PORT);
connectionThread = new Thread()
{
public void run()
{
while(true)
{
try
{
Socket newS = socket.accept();
System.out.println("Client connect");
while(!MUTEX.tryAcquire());
connections.insert(newS);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(newS.getOutputStream()));
for(String s : msgQ)
{
writer.write(s);
writer.newLine();
}
writer.flush();
MUTEX.release();
System.out.println("Client has connected");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
};
connectionThread.start();
}
catch(Exception e)
{
System.out.println(e);
}
}
public void serverRun()
{
BufferedReader reader;
while(true)
{
try
{
if(!MUTEX.tryAcquire())
{
Thread.sleep(100);
continue;
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}