-
Notifications
You must be signed in to change notification settings - Fork 0
/
webServer.java
69 lines (59 loc) · 3.54 KB
/
webServer.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
//------------------------------------------------------------------------------
// Java web server with no external dependencies.
// Philip R Brenan at appaapps dot com, Appa Apps Ltd Inc., 2024
//------------------------------------------------------------------------------
import java.io.*;
import java.net.*;
import java.util.*;
class WebServer // Web server written in Java with no dependencies.
{final static int port = 8080; // The port we are going to listen on
static String readInput(InputStream inputStream) throws Exception // Read all the bytes from the browser
{final StringBuilder B = new StringBuilder();
while(inputStream.available() > 0) B.append((char)(inputStream.read())); //Read all the available bytes
return B.toString(); // Convert to string
}
static String getMethod(String request) // Get Url from request
{final String[] lines = request.split("\\s+"); // Split into words
if (lines.length > 0) return lines[0]; // Method
return null; // Method not found
}
static String getUrl(String request) // Get Url from request
{final String[] lines = request.split("\\s+"); // Split into words
if (lines.length > 1) return lines[1]; // Url
return null; // Url not found
}
public static void main(String[] args) // Run the web server
{try
{ServerSocket serverSocket = new ServerSocket(port); // Create a server socket listening on port 8080
say("Vanina server started. Listening on port", port);
while (true)
{try(final Socket clientSocket = serverSocket.accept())
{final String request = readInput(clientSocket.getInputStream()); // Request as a string
final String method = getMethod(request);
final String url = getUrl(request);
final String[]urls = url != null ? url.split("/") : null;
say("New connection from:", clientSocket.getInetAddress());
say("Method :", method);
say("Url :", url);
String response = "HTTP/1.1 200 OK\r\n\r\n"; // Prepare response
if (urls != null && urls.length > 2)
response += "<html><body><h1>"+urls[1]+" "+urls[2]+"!</h1></body></html>";
else
response += "<html><body><h1> Hello Vanina!</h1></body></html>\n\n";
try(final OutputStream outputStream = clientSocket.getOutputStream()) // Write response to the client
{outputStream.write(response.getBytes());
outputStream.flush();
}
catch(Exception e) {e.printStackTrace();}
}
catch(Exception e) {e.printStackTrace();}
}
}
catch (Exception e) {e.printStackTrace();} // Read error
}
static void say(Object...O) // Say something
{final StringBuilder b = new StringBuilder();
for(Object o: O) {b.append(" "); b.append(o);}
System.err.println((O.length > 0 ? b.substring(1) : ""));
}
}