Using Java to implement a Web server

Source: Internet
Author: User
Tags flush sendfile socket thread class port number

The function principle of HTTP protocol

The HTTP protocol works with four steps:

1. Connection: The Web browser establishes a connection to the Web server.

2. Request: The Web browser submits the request to the Web server via the socket.

3. Answer: When a Web browser submits a request, it is routed over HTTP to the Web server. When a Web server receives a request, it handles transactions, and the processing results are passed back to the Web browser via HTTP, which displays the requested page in a Web browser.

4. Relationship Connection: When the answer is complete, the Web browser and Web server must be disconnected to ensure that other Web browsers can establish a connection with the Web server.

Second, Java implementation of the Web server program design

According to the principle of the HTTP protocol mentioned above, the method of implementing the Web server program of Get request is as follows:

1. Create the ServerSocket class object, listening on port 8080. This is taken to distinguish it from HTTP's standard TCP/IP port 80; 2. Wait, accept client connect to port 8080, get socket;3 with client connection. Creates the input stream instream and input flow OutStream associated with the socket;

The format is: Get path/filename http/1.0;4. Reads the request information submitted by a row of clients from the input stream instream associated with the socket, and the request information is in the form of a getting path/filename http/1.0;5. Gets the request type from the request information. If the request type is get, the access HTML file name is obtained from the request information. When there is no HTML file name, the INDEX.HTM1 is used as the filename; 6. If the HTML file exists, open the HTML file, send the HTTP header information and the HTML file contents back to the Web server via the socket, and then close the file, otherwise send the error message to the Web browser; 7. Closes the socket word that is connected to the appropriate Web browser.

The following program is written in accordance with the above methods and can be implemented in a multi-threaded Web server to ensure that multiple clients can connect to the Web server at the same time.

//webserver.java to write Web servers in Java


import java.io.*;


import java.net.*;


import java.util.Date;


public class webserver{


public static void Main (String args[])


  {


int i=1,port=8080;


ServerSocket Server=null;


Socketclient=null;


try{


server=new ServerSocket (PORT);


System.out.println ("Web Server is listening on port"


+server.getlocalport ());


for (;;) {


client=server.accept ();


//Accept the client's connection request


new Connection Thread (client,i). Start ();


i++;


     }


}catch (Exception e) {System.out.println (e);}


   }


  }


/*connnection Thread class complete


communication with a Web browser * *


class Connection Thread extends thread{


socket client;//Connect to a Web browser socket word


int counter;//counter


public Connection Thread (Socketcl,int c) {


CLIENT=CL;


Counter=c;


 }


public void Run ()/thread body


 {


try{


String deskip=client.getinetaddress (). toString ();


//Client IP address


int Destport=client.getport ();


//Client port number


System.out.println ("Connecction" +counter+):


connected to "+destip+" on port "+destport+");


printstream outstream=new PrintStream (Client.getooutputstream ());


datainputstreaminstream+new DataInputStream (Client.getinputstream ());


String inline=instream.readline ();


//Read request information submitted by web browser


System.out.println ("Received:" +inline);


if (getrequest (inline)) {//If a GET request


String filename=getfilename (inline);


File File=new file (filename);


if (file.exists ()) {


//If the file exists, send the file to the Web browser


System.out.println (filename+ "requested.");


outstream.println ("Http/1.0200ok");


outstream.println ("mime_version:1.0");


outstream.println ("CONTENT_TYPE:TEXT/HTM1");


int len= (int) file.length ();


outstream.println ("content_length:" +len);


outstream.println ("");


Sendfile (outstream,file);//Send file


Outstream.flush ();


}else{//file does not exist


String notfound= "<html><head><title>


not found</title></head>


<body><hl>error404-file NotFound


</hl></body></html> ";


outstream.println ("http/1.0 404 No Found");


Outstream.println ("content_type:text/html");


outstream.println ("Content_length:" +notfound.length () +2);


outstream.println ("");


outstream.println (NotFound);


Outstream.flush ();


    }


   }


long m1=1;


while (M10)


   {


if (s.substring (0,3). Equalsignorecase ("get")) return true;


   }


return false;


  }


/* Get the filename to access * *


string GetFileName (string s) {


String f=s.substring (S.indexof (') +1);


f=f.substring (0,f.indexof ('));


try{


if (f.charat (0) = = '/')


f=f.substring (1);


}catch (String indexoutofboundsexception e) {


System.out.println ("Exception:" +e);


    }


if (F.equals ("")) f= "index.html";


return F;


   }


/* Sends the specified file to the Web browser/*


void Sendfile (PrintStream outs,file File) {


try{


datainputstreamin=new DataInputStream (new FileInputStream (file));


int len= (int) file.length ();


byte buf[]=new Byte[len];


in.readfully (BUF);


Outs.write (Buf,0,len);


Outs.flush ();


In.close ();


}catch (Exception e) {


System.out.println ("Error retrieving file.");


system.exit (1);


   }


  }


 }

The connection thread line Cheng Zi class in the program is used to analyze requests submitted by a Web browser and to pass the answer back to the Web browser. where the Getrequest () method detects whether the customer's request is "get", and the GetFileName (s) method obtains the HTML file name to be accessed from the customer request information S; Sendfile () method to pass the specified file contents back to the Web browser via a socket.

Related Article

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.