-
Notifications
You must be signed in to change notification settings - Fork 0
/
Server.java
199 lines (180 loc) · 7.13 KB
/
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
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
import java.io.BufferedReader;
// import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
// import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
// import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReentrantLock;
import java.util.Date;
import java.util.TimeZone;
/**
* Server class which contains the main server loop and client thread.
*/
public class Server {
enum Nettype {
IPv4,
IPv6
}
private static final int PORT_NUMBER = 8080;
private static ServerSocket serverSocket;
private static ReentrantLock mutex;
// private static Semaphore binarySemaphore;
private static long counter = 0;
private static Socket clientSocket;
// private static byte[] clientMessageBytes;
// private static BufferedInputStream in;
// private static String clientMessage;
private static BufferedReader bufferedReader;
private static String requestLine;
private static ClientHandler[] threads;
private static int threadIndex;
/**
* Handles client connections.
*/
private static class ClientHandler extends Thread {
private Socket clientSocket;
private PrintWriter out;
private SimpleDateFormat currentTime;
private StringBuilder content;
/**
* Constructor for client connection thread.
*
* @param socket socket of client
*/
public ClientHandler(Socket socket) {
this.clientSocket = socket;
}
/**
* Called by the start() function asynchronously.
*/
public void run() {
// critical section
mutex.lock(); // using a mutex
// binarySemaphore.acquireUninterruptibly(); // using a binary semaphore
++counter;
System.out.println("Handling request #" + counter);
// binarySemaphore.release();
mutex.unlock();
try {
// use out = new DataOutputStream(this.clientSocket.getOutputStream());
// to write a byte array to a socket
out = new PrintWriter(this.clientSocket.getOutputStream(), true);
currentTime = new SimpleDateFormat(
"'Date: 'EEE, d MMM yyyy HH:mm:ss z");
currentTime.setTimeZone(TimeZone.getTimeZone("GMT"));
out.println("HTTP/1.1 200 OK");
out.println(currentTime.format(new Date()));
out.println("Server: Web Server");
out.println("Last-Modified: Thu, 4 Apr 2024 16:45:18 GMT");
out.println("Accept-Ranges: bytes");
content = new StringBuilder();
content.append("What's up? Your IP address is ");
content.append(this.clientSocket.getInetAddress().getHostAddress());
content.append("\n");
out.println("Content-Length: " + content.length());
out.println("Content-Type: text/html");
out.println();
out.print(content.toString());
out.close(); // same effect as clientSocket.shutdownOutput()
this.clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Main server loop for the web server.
*
* @param args unused
*/
public static void main(String[] args) {
Nettype netType = Nettype.IPv4;
switch (netType) {
case IPv4:
System.out.println("Using IPv4");
break;
case IPv6:
System.out.println("Using IPv6");
break;
default:
System.out.println("Unknown protocol.");
}
String[] cmd = {"date"};
try {
Process process = Runtime.getRuntime().exec(cmd);
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
System.out.println("Current time: " + output.readLine());
output.close();
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
try {
InetAddress[] ipaddrs = InetAddress.getAllByName("www.google.com");
System.out.println("IPv4 addresses associated with www.google.com:");
for (InetAddress res : ipaddrs) {
if (res instanceof Inet4Address) {
System.out.println(res.getHostAddress());
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
int port_number = 0;
if (args.length == 1) {
port_number = Integer.parseInt(args[0]) & 65535;
}
mutex = new ReentrantLock();
// binarySemaphore = new Semaphore(1);
try {
if (port_number >= 10000) {
serverSocket = new ServerSocket(port_number, Integer.MAX_VALUE,
InetAddress.getLoopbackAddress()); // InetAddress.getByName("127.0.0.1") or InetAddress.getByName("::1") for IPv6
} else {
serverSocket = new ServerSocket(PORT_NUMBER, Integer.MAX_VALUE,
InetAddress.getLoopbackAddress()); // InetAddress.getByName("127.0.0.1") or InetAddress.getByName("::1") for IPv6
}
serverSocket.setReuseAddress(true);
threads = new ClientHandler[60];
threadIndex = 0;
while (true) {
// To connect to a server:
// Socket sock = new Socket("127.0.0.1", 5000);
clientSocket = serverSocket.accept();
// clientMessageBytes = new byte[4096];
// in = new BufferedInputStream(clientSocket.getInputStream());
// use clientMessageBytes = in.readNBytes(4096); to wait for all bytes
// in.read(clientMessageBytes);
// clientMessage = new String(clientMessageBytes, StandardCharsets.UTF_8);
// requestLine = clientMessage.split("\n", 2)[0];
bufferedReader = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
requestLine = bufferedReader.readLine();
System.out.println(requestLine);
threads[threadIndex] = new ClientHandler(clientSocket);
threads[threadIndex++].start();
if (threadIndex >= 50) {
threadIndex = 0;
while (threadIndex < 50) {
threads[threadIndex++].join();
}
threadIndex = 0;
}
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
try {
serverSocket.close();
} catch (IOException exc) {
exc.printStackTrace();
}
}
}
}