A simple Java web server implementation, relatively simple, based on java.net.Socket and java.net.ServerSocket;
1. Program execution steps
1. Create a ServerSocket object;
2. Call the accept method of the ServerSocket object and wait for the connection. If the connection is successful, a Socket object will be returned, otherwise it will be blocked and waited;
3. Get the InputStream and OutputStream byte streams from the Socket object, and these two streams correspond to the request request and response response respectively;
4. Process the request: read the InputStream byte stream information, convert it into a string form, and parse it. The parsing here is relatively simple, and it only obtains the uri (uniform resource identifier) information;
5. Processing response: Based on the parsed uri information, find the requested resource resource file from the WEB_ROOT directory, read the resource file, and write it to the OutputStream byte stream;
6. Close the Socket object;
7. Go to step 2 and continue waiting for the connection request;
2. Code implementation
Server implementation:
package ex01.pyrmont;import java.net.Socket;import java.net.ServerSocket;import java.net.InetAddress;import java.io.InputStream;import java.io.OutputStream;import java.io.IOException;import java.io.File;public class HttpServer { /** * WEB_ROOT is the directory where HTML and other files are stored. The WEB_ROOT here is the webroot directory in the working directory*/ public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot"; // Close service command private static final String SHUTDOWN_COMMAND = "/SHUTDOWN"; public static void main(String[] args) { HttpServer server = new HttpServer(); // Wait for connection request server.await(); } public void await() { ServerSocket serverSocket = null; int port = 8080; try { // Server socket object serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1")); } catch (IOException e) { e.printStackTrace(); System.exit(1); } // Looping to wait for a request while (true) { Socket socket = null; InputStream input = null; OutputStream output = null; try { // Waiting for the connection, after the connection is successful, return a Socket object socket = serverSocket.accept(); input = socket.getInputStream(); output = socket.getOutputStream(); // Create Request object and parse Request request = new Request(input); request.parse(); // Check whether it is a closed service command if (request.getUri().equals(SHUTDOWN_COMMAND)) { break; } // Create Response object Response response = new Response(output); response.setRequest(request); response.sendStaticResource(); // Close socket object socket.close(); } catch (Exception e) { e.printStackTrace(); continue; } } }}Request class:
package ex01.pyrmont;import java.io.InputStream;import java.io.IOException;public class Request { private InputStream input; private String uri; public Request(InputStream input) { this.input = input; } //Read the request information from the InputStream and get the uri value from the request public void parse() { StringBuffer request = new StringBuffer(2048); int i; byte[] buffer = new byte[2048]; try { i = input.read(buffer); } catch (IOException e) { e.printStackTrace(); i = -1; } for (int j = 0; j < i; j++) { request.append((char) buffer[j]); } System.out.print(request.toString()); uri = parseUri(request.toString()); } /** * * The form of requestString is as follows: * GET /index.html HTTP/1.1 * Host: localhost:8080 * Connection: keep-alive * Cache-Control: max-age=0 * ... * The purpose of this function is to obtain /index.html string*/ private String parseUri(String requestString) { int index1, index2; index1 = requestString.indexOf(' '); if (index1 != -1) { index2 = requestString.indexOf(' ', index1 + 1); if (index2 > index1) return requestString.substring(index1 + 1, index2); } return null; } public String getUri() { return uri; }} Response class:
package ex01.pyrmont;import java.io.OutputStream;import java.io.IOException;import java.io.FileInputStream;import java.io.File;/* HTTP Response = Status-Line *(( general-header | response-header | entity-header ) CRLF) CRLF [ message-body ] Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF*/public class Response { private static final int BUFFER_SIZE = 1024; Request request; OutputStream output; public Response(OutputStream output) { this.output = output; } public void setRequest(Request request) { this.request = request; } public void sendStaticResource() throws IOException { byte[] bytes = new byte[BUFFER_SIZE]; FileInputStream fis = null; try { //Write the web file into the OutputStream byte stream File file = new File(HttpServer.WEB_ROOT, request.getUri()); if (file.exists()) { fis = new FileInputStream(file); int ch = fis.read(bytes, 0, BUFFER_SIZE); while (ch != -1) { output.write(bytes, 0, ch); ch = fis.read(bytes, 0, BUFFER_SIZE); } } else { // file not found String errorMessage = "HTTP/1.1 404 File Not Found/r/n" + "Content-Type: text/html/r/n" + "Content-Length: 23/r/n" + "/r/n" + "<h1>File Not Found</h1>"; output.write(errorMessage.getBytes()); } } catch (Exception e) { // thrown if cannot instantiate a File object System.out.println(e.toString()); } finally { if (fis != null) fis.close(); } }} 3. Results test
Access the existing resource files (note that they are stored in the webroot folder in the project directory):
Accessing non-existent resource files:
Close the server:
Reference: "In-depth Analysis of Tomcat"
@author A wind-like coder
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.