Targets
- Receive and analyze HTTP requests.
- Find the requested files on the server.
- Create response messages including requested files.
- Transfer response messages to client.
Steps
- Install Java SDK on Windows.
- Implement Web server with Java language.
- Start the Web server.
- Test the Web server.
Result
Step 1: To avoid repetition, it's not described here.
Step 2: Implement a simple multi-threaded Web server with Java.
(Reference: https://www.cnblogs.com/chenpi/p/5602171.html)
- Create a ServerSocket object.
- Call the accept() of the ServerSocket object to wait for connection from client, return a Socket object if is connected.
- Get InputStream and OutputStream from the Socket object.
- Read the request message from the InputStream and then analyze it (get the URL of the requested file).
- Find the requested file and then create a response which will be wrote to the OutputStream.
- Close the soket to ends the connection between the server and the client.
- Jump to 2, repeat this process.
import java.io.*;
import java.net.*;
import java.util.*;
public final class WebServer {
public static void main(String args[]) throws Exception {
// Set port number and establish a listen socket in server with the port.
int port = 8080;
ServerSocket serverSocket = new ServerSocket(port);
// Process HTTP service requests in an infinite loop.
while (true) {
// Listen for a TCP connection request.
Socket socket = serverSocket.accept();
// Process the request in a new thread.
HttpRequest request = new HttpRequest(socket);
Thread thread = new Thread(request);
thread.start();
//insert socket.close() here will cause exception
}
}
}
import java.io.*;
import java.net.*;
import java.util.*;
final class HttpRequest implements Runnable { // Implements the Runnable interface so that requests can be processed in different threads.
final static String CRLF = "\r\n";
final static int BUFFER_SIZE = 1024;
Socket socket;
// Constructor
public HttpRequest(Socket socket) {
this.socket = socket;
}
// Implement the run() method of the Runnable interface.
public void run() {
try {
processRequest();
}
catch(Exception e) {
System.out.println(e);
}
}
private void processRequest() throws Exception {
// Get a reference to the socket's input and output streams.
InputStream is = socket.getInputStream();
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
// Set up input stream filters.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// Get the URL information.
String requestLine = br.readLine();
StringTokenizer tokens = new StringTokenizer(requestLine);
tokens.nextToken(); // skip over the method of request line, which should be "GET" and at the head of the line
String URL = tokens.nextToken();
URL = "./WEB_APPS/" + URL;
// Attempt to find the requested file.
FileInputStream fis = null;
boolean fileExists = true;
try {
fis = new FileInputStream(URL);
}
catch (FileNotFoundException e) {
fileExists = false;
}
// Display the whole request message on the CMD window.
System.out.println();
System.out.println(requestLine);
String headerLine = null;
while ((headerLine = br.readLine()).length() != 0) {
System.out.println(headerLine);
}
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
if (fileExists) {
statusLine = "HTTP/1.1 200 OK" + CRLF;
contentTypeLine = "Content-Type: " + getContentType(URL) + CRLF;
}
else {
statusLine = "HTTP/1.1 404 Not Found" + CRLF;
contentTypeLine = "Content-Type: text/html" + CRLF;
entityBody = "<HTML><HEAD><TITLE>Not Found</TITLE></HEAD><BODY>Not Found</BODY></HTML>";
}
// Response the request.
os.writeBytes(statusLine); // method writeBytes() is implemented in class DataOutputStream
os.writeBytes(contentTypeLine);
os.writeBytes(CRLF);
if (fileExists) {
sendBytes(fis, os);
fis.close();
}
else
os.writeBytes(entityBody);
is.close();
os.close();
br.close();
socket.close();
}
private static void sendBytes(FileInputStream fis, OutputStream os) throws Exception {
byte[] buffer = new byte[BUFFER_SIZE];
int bytes = 0;
while ((bytes = fis.read(buffer)) != -1)
os.write(buffer, 0, bytes);
}
private static String getContentType(String URL) {
if(URL.endsWith(".htm") || URL.endsWith(".html"))
return "text/html";
if(URL.endsWith(".ram") || URL.endsWith(".ra"))
return "audio/x-pn-realaudio";
return "application/octet-stream" ;
}
}
Step 3: Use "javac" command to compile, and use "java" command to start the Web server.
javac WebServer.java
java WebServer
Step 4: Type the URL in the browser's address bar to test the Web server.
Requests from client showed on CMD window: