Web servers are also called hypertext transfer protocol servers. They use http to communicate with their clients. Java-based web servers will use two important classes.
java.net.Socket class and java.net.ServerSocket class, and communicate based on sending http messages.
This simple web server will have the following three classes:
*HttpServer
*Request
*Response
The application's entry In the HttpServer class, main() method creates an HttpServer instance, and then calls its await() method. As the name suggests, await() method will wait for the HTTP request on the specified port, process it, and then send a response message back to the client. It will remain waiting until the shutdown command is received.
The application only sends requests for static resources located in the specified directory, such as html files and images, and it can also display the incoming http request byte stream to the console, but it does not send any header information to the browser, such as dates or cookies, etc.
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. The InputStream object can be passed to create a Request object. read() method in the InputStream object can be called to read the original data of the HTTP request.
parse() method in the above source code is used to parse the original data of the Http request. The parse() method will call the private method parseUrI() to parse the HTTP requested URI. Apart from this, there is not much work. parseUri() method stores the URI in the variable uri, and calling the public method getUri() will return the requested uri.
Response:
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();}}}} The Response object is created in the await() method of the HttpServer class by passing the OutputStream obtained in the socket.
The Response class has two public methods: setRequest() and sendStaticResource() . setRequest() method will receive a Request object as a parameter. sendStaticResource() 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 of a specified directory, including directories specified by the public static variable final WEB_ROOT and all subdirectories.
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 output of the corresponding console:
In this way, a simple http server is done.
The above is all about Java implementation of a simple web server instance analysis, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!