Java Socket Programming (v) Simple Web server _java programming

Source: Internet
Author: User
Tags http request
Article Source: ASPCN Author: Sun Wen

A simple Web server

A simple Web server will be built from listing 9.2. Of course, the method and response events must also be improved. A simple server does not parse and store the request headers. The new Web server will analyze and store requests for future processing. To achieve this goal, You must have a class that contains HTTP requests.

HttpRequest class

Listing 9.5 Lists a complete HttpRequest class. This class must include all the information required by a request header.

List of 9.5.HTTPrequest classes.

Import java.io.*;
Import java.util.*;
Import java.net.*;
Import Namevalue;
/**
* This class has all the information for an HTTP request
*/
public class HttpRequest
{
public String version;
Public String method;
public String file;
Public Socket Clientsocket;
public DataInputStream Inbound;
Public Namevalue headerpairs[];
/**
* Create an instance of this class
*/
Public HttpRequest ()
{
Version = NULL;
method = null;
FILE = null;
Clientsocket = null;
inbound = null;
inbound = null;
Headerpairs = new Namevalue[0];
}
/**
* Add a name/value pair to the core array
*/
public void Addnamevalue (string name, String value)
{
Try
{
Namevalue temp[] = new namevalue[headerpairs.length + 1];
System.arraycopy (headerpairs, 0, temp, 0, headerpairs.length);
temp[Headerpairs.length] = new Namevalue (name, value);
Headerpairs = temp;
}
catch (NullPointerException NPE)
{
System.out.println ("NullPointerException while adding Name-value:
"+ NPE);
}
}
/**
* Return this class as a string
*/
Public String toString ()
{
String s = method + "" + file + "" + version + \ n;
for (int x = 0; x < Headerpairs.length + +)
s + + headerpairs[x] + "\ n";
return s;
}
}

The Namevalue class simply stores two strings: name and value. When a new pair is to be added, a new array is assigned. The new array accepts the old array and the new member. The old array is then overwritten by a new object.

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.