Implement one simple HTTP Server Based on Java

Source: Internet
Author: User

This article will introduce in detail how to implement a simple HTTP Server Based on the Java language. This article 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 this server with multi-thread technology to a better server.

Because the Web server uses the HTTP protocol for communication, it is also called the HTTP server. Http uses a reliable TCP connection to work. It is a connection-oriented communication method, this means that the client and the server establish their own connection each time they communicate, and it is a stateless connection. After data transmission is completed, the connection between the client and the server is immediately closed, which can save server resources, if you need to transmit a large amount of data, you can set connection = keep-alive in the request header to reuse this connection channel. Two important concepts in HTTP are request and response. For more information about HTTP, see http://www.w3.org/protocols/http/1.1/rfc2616.20.

An HTTP request consists of three important parts:
Method-Uri-Protocol/version
Request headers
Entity body
The following is an example of an HTTP request:
Post/servlet/Default. jsp HTTP/1.1
Accept: 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 is method-Uri-Protocol/version, which is a very important part. You need to read the method of data transmission from the client, Uri, protocol, and version, here are post/servlet/default. jsp HTTP/1.1. Our simple server idea is to get the URI from the request and find this resource on your server. For example, it is a static HTML page, then, send it to the browser. Remember that the URI is relative to the root directory of your HTTP server, so it starts. The following section describes the request header information in the form of name: value. There is a blank line between the header and the entity body called CRLF, which is used to mark the beginning of the entity body, which means the following is the transmitted data.

The HTTP response is very similar to the request, which also includes three parts:
Protocol-status code-Description
Response Headers
Entity body
The following is a specific example:
HTTP/1.1 200 OK
Server: Microsoft-Microsoft IIS/4.0
Date: Mon, 3 Jan 1998 13:13:33 GMT
Content-Type: text/html
Last-modified: Mon, 11 Jan 1998 13:23:42 GMT
Content-Length: 112

Something in HTML style ......................

Generally, we need to determine the status code of the response to determine the next operation. For example, 200 indicates that the connection is successful. Now you should know why. There is also a CRLF split between the header and the 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 end of the network, but it does not depend on the programming language, you can use Java and C to communicate through socket. in Java, Java uses 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, and port represents the port, such as 80. When we create a socket instance, we can communicate. If you want to communicate based on bytes, you can call getoutputstream () and getinputstream () to obtain the objects of outputstream and inputstream. If you use character-based communication, you can use printwriter and bufferedreader for secondary packaging. For example, printwriter PW = new printwriter (socket. getoutputstream (), true ). The following is a simple code snippet that uses Socket Communication to send an HTTP request 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 (New inputstreamreader (socket. getinputstream ()));

// Send an HTTP request to the Web server
Out. println ("Get/index. jsp HTTP/1.1 ");
Out. println ("Host: localhost: 8080 ");
Out. println ("connection: Close ");
Out. println ();

// Read the response
Boolean 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 console
System. Out. println (sb. tostring ());
Socket. Close ();

Next we will introduce the use of the serversocket class corresponding to the socket class. Different from socket, serversocket represents the server, because it must constantly monitor whether a client is connected to a port. By calling the serversocket constructor, we can establish a server that listens to a specific port. For example
New serversocket (8080, 1, inetaddress. getbyname ("127.0.0.1 "));
In this way, we have set up serversocket on port 8080 of the local machine. After you call the serversocket accept () method, this method returns a socket object only when a connection comes in, in this way, you can use this instance to accept or send data. Remember to call the Clos () method to release resources after data transmission is complete.

This article mainly paves the way for the implementation of the HTTP server. In the subsequent articles, we will mainly describe how to implement and run the HTTP server based on Java.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.