Handwriting a simple HTTP server

Source: Internet
Author: User

What is the HTTP protocol?

H TTP protocol: For browser clients and format specification for data transfer between server side

Http is an object-oriented protocol belonging to the application layer, which is suitable for distributed hypermedia information System because of its simple and fast way. It was proposed in 1990, after several years of use and development, has been continuously improved and expanded. Currently used in the WWW is the sixth edition of Http/1.0, http/1.1 standardization work is in progress, and Http-ng (Next Generation of HTTP) has been proposed.
The main features of the HTTP protocol can be summarized as follows:
1. Support client/server mode.
2. Simple and fast: When a customer requests a service from the server, it simply transmits the request method and path. The request method commonly has, POST. Each method specifies a different type of contact between the customer and the server. Because the HTTP protocol is simple, the HTTP server's program size is small, so the communication speed is fast.
3. Flexible: HTTP allows the transfer of any type of data object. The type being transmitted is marked by Content-type.
4. No connection: The meaning of no connection is to limit the processing of only one request per connection. When the server finishes processing the customer's request and receives the customer's answer, the connection is disconnected. In this way, the transmission time can be saved.
5. Stateless: The HTTP protocol is a stateless protocol. Stateless means that the protocol has no memory capacity for transactional processing. A lack of state means that if the previous information is required for subsequent processing, it must be re-routed, which may cause the amount of data to be transferred per connection to increase. On the other hand, it responds faster when the server does not need the previous information.

HTTP is implemented using the TCP protocol in the socket, based on request (client), response (server side)

Example : http://127.0.0.1:8080/project path

The HTTP protocol is divided into request message and response message.

Request Mode Get, Post, Delete ... ..

default Http Request Parameters ( Request message )

get/http/1.1

host:127.0.0.1:8080

Connection:keep-alive

Cache-control:max-age=0

Upgrade-insecure-requests:1

user-agent:mozilla/5.0 (Windows NT 6.1; Win64; x64) applewebkit/537.36 (khtml, like Gecko) chrome/53.0.2783.4 safari/537.36

accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

Accept-encoding:gzip, deflate, SDCH

accept-language:zh-cn,zh;q=0.8

cookie:hm_lvt_b43c1c82b09cda6b125e6981fbde442c=1487946887,1487950668,1488114252; cnzzdata1259976290=1895288300-1478441025-%7c1488116464

Http Response Messages

The HTTP response message corresponds to the HTTP request message and is divided into three parts.

  1, Response line

  2. Response Head

  3. Response Body

Project Structure diagram:

On the Code

Encapsulates the data class for the response
Package Cn.liuzhiw.server;import Java.io.bufferedwriter;import Java.io.ioexception;import java.io.OutputStream; Import Java.io.outputstreamwriter;import java.util.date;/** * Encapsulates the data class of the response * Created by Liu Zhiwei on 2018/4/24.    */public class Response {//Space private final String blank= "";    NewLine private final String br= "\ r \ n";    Show HTTP response header private StringBuffer responsedata;    Package Web information private StringBuffer responseinfo;    Character buffered output stream private bufferedwriter bufferedwriter;    The length of the response is private long Len;        Initialize configuration public Response (OutputStream outputstream) {responsedata=new stringbuffer ();        Responseinfo=new StringBuffer ();    Bufferedwriter=new BufferedWriter (New OutputStreamWriter (OutputStream));        }//Create header information private void Createheadinfo (int code) {responsedata.append ("http/1.1");        Responsedata.append (BLANK);        Responsedata.append (code + ""). Append (BLANK); Switch (code) {Case 200:responsedata.append ("OK ");            Break                Case 404:responsedata.append ("not Found");            Break                Case 500:responsedata.append ("Server Error");            Break        Default:break;        } responsedata.append ("Date:"). Append (new Date ()). append (BR);        Responsedata.append ("Content-type:text/html;charset=utf-8"). Append (BR);        Responsedata.append ("Content-length:"). Append (len). Append (BR);    Responsedata.append (BR); }/** * Fills the page class capacity * @param str * @return */public Response print (String str) {Responseinfo.app        End (str);        Len + = Str.getbytes (). length;    return this; /** * Send data * @throws IOException */public void connect (int code) throws IOException {Createhe        Adinfo (code);        Bufferedwriter.append (Responsedata.tostring ());        Bufferedwriter.append (Responseinfo.tostring ());  Refresh Bufferedwriter.flush ();      Close Bufferedwriter.close (); }}

  

Server Core Configuration Class
Package Cn.liuzhiw.server;import Java.io.*;import Java.net.serversocket;import java.net.socket;import java.util.date;/** * Server Core Configuration class * Created by Liu Zhiwei on 2018/4/24.    */public class Server4 {//socket server private serversocket serversocket;    Port number private final int port=8080;        /** * Start Server */public void Start () throws IOException {System.out.println ("Server started successfully ...");        Monitoring Server Serversocket=new ServerSocket (PORT);        Accept client Data acceptclient ();    Close link closeserver (); }/** * accepts client data * @throws IOException */public void acceptclient () throws IOException {//Get sock        Et client object Socket accept = Serversocket.accept ();        Get input stream InputStream InputStream = Accept.getinputstream ();        byte []data=new byte[20480];        int read = Inputstream.read (data);        String message = new string (data, 0, read);        SYSTEM.OUT.PRINTLN ("The data sent by the client:" +message); Response Back Data Response respOnse=new Response (Accept.getoutputstream ()); Response.print ("

  

Server Startup Portal
Package Cn.liuzhiw.app;import cn.liuzhiw.server.server4;import java.io.ioexception;/** * Server boot entry * Created by 刘志威 on 2018 /4/24. */public class App {public    static void Main (string[] args) throws IOException {        Server4 server=new Server4 (); 
   
    server.start ();    }}
   

Page for HTML request

<HTML><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"><title>HTTP Server Post method submission parameters</title></Head><Body>    <Pre>method: Request Get/post get: Small amount of data, security is not high by default post: Large volume, relatively high security action: The requested server path ID: Number: Front-end distinguishing unique, JS using NA        Me: The name backend (server) distinguishes between uniqueness, get the value as long as the data submitted to the background, must exist name; </Pre>   <formAction= "Http://127.0.0.1:8080/index"Method= "POST">User name:<inputtype= "text"name= "Uname"ID= "Uname">user face:<inputtype= "Password"name= "pwd"ID= "pwd">   <inputtype= "Submit">   </form></Body></HTML>

Page effects and background effects

Handwriting a simple HTTP server

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.