Java implementation of simple Web server _java

Source: Internet
Author: User
Tags webp

It is well known that the communication between the Web server and the client is using the HTTP protocol. HTTP is a standard (TCP) for both client and server-side requests and responses. Because the HTTP protocol is based on the TCP protocol, I will use the socket in Java to complete this simple Web server. For more detailed information on HTTP, you can consult the relevant information to understand.
Before the server is written, let's take a look at the rules for how browsers communicate with the server.
First, we use ServerSocket to simulate a server, access through the browser, to view the content of the browser request:

Import Java.io.BufferedWriter;
Import Java.io.InputStream;
Import Java.io.OutputStreamWriter;
Import java.net.InetAddress;
Import java.net.InetSocketAddress;
Import Java.net.ServerSocket;
Import Java.net.Socket;

Import Org.junit.Test;

/**
 * HTTP protocol Test * * 
 @author Jianggujin * */Public
class Hqhttpprotocoltest
{
 @Test public
 void Server () throws Exception
 {
  ServerSocket serversocket = new ServerSocket (80); C20/>socket Socket = serversocket.accept ();
  InputStream stream = Socket.getinputstream ();
  int r =-1;
  while ((R = Stream.read ())!=-1)
  {
   System.out.print ((char) r);
  }
 }


Run using JUnit and access through the browser:http://127.0.0.1, we can see the console output browser request content as follows:

get/http/1.1
host:127.0.0.1
connection:keep-alive
accept:text/html,application/xhtml+xml, application/xml;q=0.9,image/webp,*/*;q=0.8
user-agent:mozilla/5.0 (Windows NT 5.1) applewebkit/537.36 (KHTML, Like Gecko) chrome/31.0.1650.63 safari/537
accept-encoding:gzip,deflate,sdch
accept-language: zh-cn,zh;q=0.8

To better analyze the request content, we write an HTML page to submit some data and view the request again:

<! DOCTYPE html>
 
 

Enter Bob in the input box, click the button submit, and watch the console output:

POST/?test=123 http/1.1
host:127.0.0.1
connection:keep-alive
content-length:8 cache-control
: Max-age=0
accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: Null
user-agent:mozilla/5.0 (Windows NT 5.1) applewebkit/537.36 (khtml, like Gecko) chrome/31.0.1650.63 safari/537< c8/>.36
content-type:application/x-www-form-urlencoded
accept-encoding:gzip,deflate,sdch
accept-language:zh-cn,zh;q=0.8

Name=bob

Let's analyze This request:
The first line: consists of three parts, the middle separated by a space, the first is divided into the request method (get, POST), the second part is the request path and query parameters, the third part of the HTTP protocol version (http/1.1)
Second line to line tenth: requested header information, request header name and value passed between: delimited
Line 11th: blank line
Line 12th: Content of the form submitted
In conclusion, we can get the following conclusions: Request information first behavior request method, request path and query parameters, HTTP protocol version, through \ r \ n line after the request header information, the header information through the \ r \ n line, the request header information after the end followed by a blank line, empty line followed by a behavior request data, It should be noted that this only simulates the simplest form submission, as for complex file submissions, which are not discussed here, the request content format is slightly different.
Now that we know what the client is requesting, we'll look at the format that the server responds to after receiving the request, we create a new Web project for testing, and edit the HTML page as follows:

<! DOCTYPE html>
 
 

Start the server, and then write the client test code to obtain service-side return data:

Import Java.io.BufferedWriter;
Import Java.io.InputStream;
Import Java.io.OutputStreamWriter;
Import Java.net.ServerSocket;

Import Java.net.Socket;

Import Org.junit.Test; /** * HTTP Protocol Test * * @author Jianggujin * */public class Hqhttpprotocoltest {public void server () throws Exceptio
  n {serversocket serversocket = new ServerSocket (80);
  Socket socket = serversocket.accept ();
  InputStream stream = Socket.getinputstream ();
  Bufferedinputstream InputStream = new Bufferedinputstream (stream);
  int r =-1;
  while ((R = Stream.read ())!=-1) {System.out.print ((char) r);
  @Test public void Client () throws Exception {socket socket = new Socket ("127.0.0.1", 80);
  BufferedWriter writer = new BufferedWriter (New OutputStreamWriter (Socket.getoutputstream ()));
  Writer.write ("get/servlet/test.html http/1.1\r\n");
  Writer.write ("host:127.0.0.1\r\n");
  Writer.write ("connection:keep-alive\r\n"); Writer.write ("Accept:text/html,application/xhtml+xml,aPplication/xml;q=0.9,image/webp,*/*;q=0.8\r\n "); Writer.write ("user-agent:mozilla/5.0 (Windows NT 5.1) applewebkit/537.36 (khtml, like Gecko) chrome/31.0.1650.63 Safari
  /537.36\r\n ");
  Writer.write ("accept-encoding:gzip,deflate,sdch\r\n");
  Writer.write ("accept-language:zh-cn,zh;q=0.8\r\n");
  Writer.write ("\ r \ n");
  Writer.flush ();
  InputStream stream = Socket.getinputstream ();
  int r =-1;
  while ((R = Stream.read ())!=-1) {System.out.print ((char) r);

 }
 }
}

Run the program to get the server return content as follows:

http/1.1 OK
server:apache-coyote/1.1
accept-ranges:bytes
etag:w/"129-1456125361109"
Last-modified:mon, Feb 2016 07:16:01 GMT
content-type:text/html
content-length:129 Date:mon
, Feb 201 6 08:08:32 GMT

<! DOCTYPE html>
 
 

Again, let's analyze This return message:
The first line consists of three parts, the middle is separated by the space, the first part is the HTTP protocol version (http/1.1), the second part is the response status code, the third part is the response status description
The second line to the seventh behavior Response header information, the response header name is passed between the values: separating
Line eighth: Blank line
Line nineth to end: response content
In conclusion, we can get the following conclusions: Request information first behavior HTTP protocol version, Response status code, response status description, through \ r \ n After line change followed by the response header information, each header information through the \ r \ n line, the response header information after the end followed by a blank line, the blank line followed by the response data, need to pay attention to , in addition to this response, there are other appropriate ways, such as chunk, not discussed here, you can access the relevant information.

So far, we have analyzed the client's request content format and the corresponding content of the service side format, this is the end of this article, I hope to help you learn.

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.