A simple Web server

Source: Internet
Author: User

A simple Web server
  • The Web server is also known as the Hypertext Transfer Protocol (Hypertext Transfer Protocol) server because it communicates using HTTP and the client (usually a Web browser)
  • The Javaweb-based server uses two important classes: the Java.net.Socket class and the Java.net.ServerSocket class, and communicates by sending an HTTP message.

    1.1 HTTP
  • HTTP allows Web servers and browsers to send and receive data over the Internet, which is based on a "request-response" protocol.
  • HTTP uses a reliable TCP connection, and the TCP protocol uses the TCP 80 port by default.
  • There is always a client in HTTP that initializes a transaction by establishing a connection and sending an HTTP request. The client or server can close the connection early
  • 1.1.1 HTTP Requests
    • The HTTP request contains three parts:
      1. Request Method--Uniform Resource Identifier uri--Protocol/version
      2. Request Header
      3. Entity
    • Each HTTP request can use one of the methods specified in the HTTP standard. HTTP1.1 Supported methods: Get,post,head,options,put,delete,trace
    • URI Specifies the full path of the Internet resource. The URI is usually the relative path to the server root directory
    • The request header contains information about the client environment and the requesting entity
    • There is a blank line between the request header and the entity, the empty line has only CRLF characters , and Crlf tells the HTTP server to ask where the entity body starts
  • 1.1.2 HTTP Response
    • The HTTP response consists of three parts:
      • Protocol--Status code--description
      • Response header
      • Response entity
  • 1.2 Socket Class
  • Sockets are power outages for network connections. Sockets enable applications to read and write data from the network.
  • Send or receive messages between applications, you need to know the IP address and port number of the socket in the other application. In Java, sockets are represented by Java.net.Socket
  • Create a socket:
    • public Socket(java.net.String host,int port)
  • When you create a successful socket instance, you can use that instance to send or accept a byte stream. To send a byte stream you need to call the Getoutputstream method of the socket class to get a OutputStream object. Receive byte stream use getInputStream method to get input stream InputStream object
  • ServerSocket class
  • The socket represents a client socket, which is the socket that is created when you want to connect to a remote server application.
  • If you want to implement a server that sends a response to a client, you need another socket, serversocket. Because the server needs to be on standby, wait for the client to initiate the connection.
  • The ServerSocket class and the socket class are not the same. The server socket needs to wait for a connection from the client. When a server socket receives a connection request, a socket instance is created to handle communication with the client.
  • To create a server socket, you can use any of the 4 constructors provided by the ServerSocket class: The port number that you want to indicate the IP address and the server socket to listen on.
    • //如果主机只有一个IP 地址, 那么默认情况下, 服务器程序就与该IP 地址绑定. ServerSocket 的第 4 个构造方法 ServerSocket(int port, int backlog, InetAddress bingAddr) 有一个 bindAddr 参数, 它显式指定服务器要绑定的IP 地址, 该构造方法适用于具有多个IP 地址的主机. 假定一个主机有两个网卡, 一个网卡用于连接到 Internet, IP为 222.67.5.94, 还有一个网卡用于连接到本地局域网, IP 地址为 192.168.3.4. 如果服务器仅仅被本地局域网中的客户访问, 那么可以按如下方式创建 ServerSocket:new ServerSocket(800010, InetAddress.getByName("192.168.3.4"));
      1.3 Applications
  • A Web server application contains three classes:
    • Httpserver
    • Request
    • Response
    • Application entry point (static Main method) in the Httpserver class, the main method creates an Httpserver instance and then calls its await method. The method waits for an HTTP request on the specified port, processes it, and then sends the response message to the client.
  • 1.3.1 Httpserver Class
    • "' Java
      Package Ex01.pyrmont;

      Import Java.net.Socket;
      Import Java.net.ServerSocket;
      Import java.net.InetAddress;
      Import Java.io.InputStream;
      Import Java.io.OutputStream;
      Import java.io.IOException;
      Import Java.io.File;

      public class Httpserver {

      /** Web_root is the directory where we HTML and other files reside.* for this package, Web_root is the "Webroot" Directo  Ry under the working* directory.* the working directory is the location of the file system* from where the Java command was invoked.*/public static final String web_root = System.getproperty ("User.dir") + File.separator + "webroot";//sh Utdown commandprivate static final String Shutdown_command = "/shutdown";//The SHUTDOWN COMMAND receivedprivate boolean s    Hutdown = 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 (IOException e) {e.printstacktrace ();    System.exit (1);        }//Loop waiting for a request 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 ();            Close the socket Socket.close ();        Check if the previous URI is a shutdown command shutdown = Request.geturi (). Equals (Shutdown_command);            } catch (Exception e) {e.printstacktrace ();        Continue }    }}
      }
  • 1.3.2 Request Class
  • The request class represents an HTTP request. You can pass a InputStream object to create a request object. Use the Read method to read data from http:
    • "' Java
      Package Ex01.pyrmont;

      Import Java.io.InputStream;
      Import java.io.IOException;

      public class Request {

      private InputStream input;private String uri;public Request(InputStream input) {    this.input = input;}public void parse() {//解析HTTP请求中原始数据    // 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 (IOException 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());}private 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 uri;}

      }

      1.3.3 Response Class
  •     Package Ex01.pyrmont;    import Java.io.OutputStream;    import java.io.IOException;    import Java.io.FileInputStream;    import Java.io.File;    /*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 classResponse {Private Static Final intBuffer_size =1024x768;        Request request; OutputStream output; PublicResponse (OutputStream output) { This.Output= output; } Public void setrequest(Request request) { This.Request= Request; } Public void Sendstaticresource()throwsIOException {byte[] bytes =New byte[Buffer_size]; FileInputStream FIS =NULL;Try{File File =NewFile (Httpserver.Web_root, request.GetURI());if(file.exists()) {FIS =NewFileInputStream (file);intch = fis.Read(Bytes,0, buffer_size); while(ch!=-1) {output.Write(Bytes,0, ch); ch = fis.Read(Bytes,0, buffer_size); }            }Else{//File not foundString errormessage ="http/1.1 404 File Not Found\ r \ n"+"Content-type:text/html\ r \ n"+"Content-length:23\ r \ n"+"\ r \ n"+"; Output.Write(ErrorMessage.getBytes()); }            }Catch(Exception e) {//Thrown if cannot instantiate a File objectSystem. out.println(E.toString() ); }finally{if(fis!=NULL) fis.Close(); }        }    }

    Run results

A simple Web 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.