This article will detail how to implement a simple HTTP server based on Java language. The text will mainly introduce three aspects: 1) Basic knowledge of the HTTP protocol, 2) java.net.Socket class, 3) java.net.serversocket class After reading this article, you can rewrite a better server with multi-threaded technologies.
Since the web server uses the HTTP protocol communication, it also called the HTTP server. HTTP uses a reliable TCP connection to work, it is a connection-oriented manner, which means that the client and server build your own connection, it It is also a stateless connection. When the data transfer is completed, the connection is turned off immediately, which saves the resources of the server. Of course, if you need to transfer a lot of data, you can set up the connection = Keep-alive to the REQUEST header = Keep-alive makes Reuse this connection channel. Two concepts in the HTTP protocol are: requests (Request) and (respond) this is also what I am here. If you want to know more about http, please refer to http://www.w3.org/ Protocols / http / 1.1 / rfc2616.pdf.
An HTTP request consists of three important parts: Method-Uri-Protocol / Version Request Headers Entity Body The following is an example of HTTP request: post /servlet/default.jsp http / 1.1accept: text / plain; text / html accept language: en-gb Connection: Keep-Alive Host: localhost Referer: http: //localhost/ch8/SendDetails.htm User-Agent: Mozilla / 4.0 (compatible; MSIE 4.01; Windows 98) Content-Length: 33 Content-Type : Application / X-WWW-FORM-URLENCODED ACCEPT-ENCODING: GZIP, Deflate
LastName = FRANKS & FIRSTNAME = Michael, the first line of the first line is Method-Uri-Protocol / Version, which is a very important part, you need to read the way client data transfer, URI, and protocols and versions, here are Post / servlet, respectively /Default.jsp http / 1.1, our simple server's ideas is to find this resource on your server after getting URI from Request, such as a static HTML page, and send it to the browser. Remember the URI is the root directory of your HTTP server, so starting with /. The next part is requested header information. They are all constructed in Name: Value, which is not more introduced here. There is a hollow between Header and Entity Body called CRLF, which is used to mark the beginning of Entity Body, meaning the following is the transmitted data.
The HTTP response and request are very similar, and three parts are also included: Protocol-Status Code-Description Response Headers Entity Body The following is a specific example: HTTP / 1.1 200 OKServer: Microsoft-IIS / 4.0Date: Mon, 3 Jan 1998 13: 13:33 GMTCONTENT-TYPE: TEXT / HTMLLAST-Modified: Mon, 11 Jan 1998 13:23:42 GMTCONTENT-Length: 112something in html style ................... ...
Usually we need to judge the status code of the response in the J2ME network to determine the next step, such as 200 representative connection success. Now you should clear why do you do this. There is also a CRLF segmentation in Header and Entity Body.
Now let's take a look at the Socket class in Java. Socket is actually an abstraction of the programming language. It provides the possibility of access to the upper end of the network, but it does not depend on programming language, you can use Java and C. Language communicates via Socket, in Java is implemented through java.net.socket, when you want to build a socket, you just need to call its constructor public socket (String Host, Int port), where Host Represents the address or name of the target host, Port represents port, such as 80. When we created an instance of a socket, we can communicate, if you want to communicate based on bytes, you can get OutputStream and InputStream objects by calling getOutputStream () and getInputStream (), if you are character based on characters If you communicate, then you can use PrintWriter and BufferedReader for secondary packaging, such as PrintWriter PW = New PrintWriter (Socket.getOutputStream (), true). Below is a simple code snippet using the socket communication, implements the ability to send HTTP requests to 127.0.0.1:8080.
Socket socket = new Socket ( "127.0.0.1", "8080"); OutputStream os = socket.getOutputStream (); boolean autoflush = true; PrintWriter out = new PrintWriter (socket.getOutputStream (), autoflush); BufferedReader in = new BufferedReader (NEWET.GETITINPUTSTREAM ()));
// send an http request to the web serverout.println ("get /index.jsp http / 1.1"); Out.println ("Host: localhost: 8080); Out.println (" Connection: Close "); OUT .println ();
// read the responseBoolean loop = true; stringbuffer sb = new stringbuffer (8096);
While (loop) {if (in.ready ()) {INT i = 0; while (i! = - 1) {i = in.read (); sb.append ((char) i);} loop = false Thread.currentthread (). Sleep (50);} // Display the response to the out consolesystem.out.println (sb.tostring ()); socket.close ();
Next, the use of the ServerSocket class corresponding to the Socket class is different. Different from the socket represent the client, ServerSocket is on behalf of the server side, because it must have a client connection in a port. By calling a constructor constructor we can build a SERVER that holds a specific port. For example, New Serversocket (8080, 1, inetaddress.getbyname); so we set up Serversocket in the 8080 port of this unit. When you call the ServerSocket's Accept () method, this method only returns a socket object when it comes in, so you can use this instance to accept or send data. Remember to remember to call the Clos () method to release the resource when we transfer the data.
This paper is mainly to make a paving at the implementation of the HTTP server, which will mainly tell the HTTP server to implement and run the Java-implemented HTTP server.