Java implements a simple web server

A web server, also known as a hypertext transfer protocol server, uses http to communicate with its clients. A java-based web server uses two important classes,

The java.net.Socket class and the java.net.ServerSocket class communicate based on sending http messages.

This simple web server will have the following three classes:

*HttpServer

*Request

*Response

The entry of the application is in the HttpServer class. The main() method creates an HttpServer instance, and then calls its await() method. As the name implies, the await() method will be executed on the specified port.

It waits for the HTTP request, processes it, and sends the response back to the client, which will remain in the waiting state until the close command is received.

The application only sends requests for static resources located in the specified directory, such as html files and images, it can also display the incoming http request byte stream to the console, however, it does not send

Any header information to the browser, such as date or cookies, etc.

The source code for these classes is as follows:

Request:

package cn.com.server;

import java.io.InputStream;

public class Request {
	private InputStream input;
	
	private String uri;
	
	public Request(InputStream input){
		this.input=input;
	}
	
	public void parse(){
		//Read a set of characters from the socket
		StringBuffer request=new StringBuffer(2048);
		int i;
		byte[] buffer=new byte[2048];
		try {
			i=input.read(buffer);
		} catch (Exception 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());
	}
	
	public 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 this.uri;
	}
}
The Request class represents an HTTP request. You can pass an InputStream object to create a Request object, and you can call the read() method in the InputStream object to read the HTTP request.

the original data.

The parse() method in the above source code is used to parse the raw data of the Http request. The parse() method will call the private method parseUrI() to parse the URI of the HTTP request. In addition, there is no

Doing too much work, the parseUri() method stores the URI in the variable uri, and calling the public method getUri() returns the requested uri.

Response:

<span style="font-size:10px;">package cn.com.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 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 {
			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, BUFFER_SIZE);
					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) {
			System.out.println(e.toString());
		}finally{
			if(fis!=null){
				fis.close();
			}
		}
	}
}</span><span style="font-size:24px;">
</span>
The Response object is created in the await() method of the HttpServer class by passing in the OutputStream obtained from the socket.

The Response class has two public methods: setRequest() and sendStaticResource(). The setRequest() method will receive a Request object as a parameter, and sendStaticResource()

The method is used to send a static resource to the browser, such as an Html file.

HttpServer:

package cn.com.server;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServer {
	/**
	 * WEB_ROOT is the directory where our html and other files reside.
	 * For this package,WEB_ROOT is the "webroot" directory under the
	 * working directory.
	 * the working directory is the location in the file system
	 * from where the java command was invoke.
	 */
	public static final String WEB_ROOT=System.getProperty("user.dir")+File.separator+"webroot";
	
	private static final String SHUTDOWN_COMMAND="/SHUTDOWN";
	
	private boolean shutdown=false;
	
	public static void main(String[] args) {
		HttpServer server=new HttpServer();
		server.await();
	}
	
	public void await(){
		ServerSocket serverSocket=null;
		int port=8080;
		try {
			serverSocket=new ServerSocket(port,1,InetAddress.getByName("127.0.0.1"));
		} catch (Exception e) {
			e.printStackTrace ();
			System.exit(0);
		}
		while(!shutdown){
			Socket socket=null;
			InputStream input=null;
			OutputStream output=null;
			try {
				socket=serverSocket.accept();
				input=socket.getInputStream();
				output=socket.getOutputStream();
				//create Request object and parse
				Request request=new Request(input);
				request.parse();
				
				//create Response object
				Response response=new Response(output);
				response.setRequest(request);
				response.sendStaticResource();
			} catch (Exception e) {
				e.printStackTrace ();
				continue;
			}
		}
	}
}
This class represents a web server that can handle requests for static resources in a specified directory, including the directory and all its subdirectories specified by the public static variable final WEB_ROOT.

Now create an html page in webroot, named index.html, the source code is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>Hello World!</h1>
</body>
</html>

Now start the web server and request the index.html static page.

The corresponding console output:


In this way , a simple http server is completed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325391365&siteId=291194637