Simple java web server instance

Source: Internet
Author: User

Programming Web servers implemented in java is mainly implemented through java socket programming. Using java socket programming can not only write web servers, but also write other network applications.

WebServer. java

Package webbook. chapter2;

Import java. io. IOException;
Import java.net. ServerSocket;
Import java.net. Socket;

Public class WebServer {
/** Default server Socket Port Number */
Public static final int HTTP_PORT = 8080;
Private ServerSocket serverSocket;

Public void startServer (int port ){
Try {
ServerSocket = new ServerSocket (port );
System. out. println ("Web Server startup on" + port );
While (true ){
Socket socket = serverSocket. accept ();
// Process customer requests through threads
New Processor (socket). start ();
}
} Catch (IOException e ){
E. printStackTrace ();
}
}

/**
* WebServer startup method. You can use the command line parameter to specify the port number used by the current Web server.
*/
Public static void main (String [] argv) throws Exception {
WebServer server = new WebServer ();
If (argv. length = 1 ){
Server. startServer (Integer. parseInt (argv [0]);
} Else {
Server. startServer (WebServer. HTTP_PORT );
}
}
}
Processor. java

Package webbook. chapter2;

Import java. io .*;
Import java.net. Socket;

/**
* Thread class for processing an HTTP user request.
*/
Public class Processor extends Thread {
Private PrintStream out;
Private InputStream input;
/** The default server stores the Directory D: \ eclipse3.4 \ workspace03 */
Public static final String WEB_ROOT = "d :\\ eclipse3.4 \ workspace03 \ webserver2 \ htdocs ";

Public Processor (Socket socket ){
Try {
Input = socket. getInputStream ();
Out = new PrintStream (socket. getOutputStream ());
} Catch (IOException e ){
E. printStackTrace ();
}
}

Public void run (){
Try {
String fileName = parse (input );
ReadFile (fileName );
} Catch (IOException e ){
E. printStackTrace ();
}
}

/**
* Parse all HTTP requests sent by the client. If the request complies with the HTTP protocol, the name of the file to be accessed by the client is analyzed and the file name is returned.
*/
Public String parse (InputStream input) throws IOException {
BufferedReader in = new BufferedReader (new InputStreamReader (input ));
String inputContent = in. readLine ();
If (inputContent = null | inputContent. length () = 0 ){
SendError (400, "Client invoke error ");
Return null;
}
// Analyze the HTTP information requested by the customer and find out which file you want to access,
// The HTTP request sent should be in three parts.

String request [] = inputContent. split ("");
If (request. length! = 3 ){
SendError (400, "Client invoke error ");
Return null;
}
// The first part is the request method.
String method = request [0];
// The second part is the request file name.
String fileName = request [1];
// The third part is the HTTP Version Number.
String httpVersion = request [2];
System. out. println ("Method:" + method + ", file name:" + fileName + ", HTTP version:" + httpVersion );
Return fileName;
}

/**
* Process the request to call a file
*/
Public void readFile (String fileName) throws IOException {
File file = new File (Processor. WEB_ROOT + fileName );
If (! File. exists ()){
SendError (404, "File Not Found ");
Return;
}
// Read the object content to the in object.
InputStream in = new FileInputStream (file );
Byte content [] = new byte [(int) file. length ()];
In. read (content );
Out. println ("HTTP/1.0 200 sendFile ");
Out. println ("Content-length:" + content. length );
Out. println ();
Out. write (content );
Out. flush ();
Out. close ();
In. close ();
}

/**
* Sending error messages
*/
Public void sendError (int errNum, String errMsg ){
Out. println ("HTTP/1.0" + errNum + "" + errMsg );
Out. println ("Content-type: text/html ");
Out. println ();
Out. println ("Out. println ("<meta content = 'text/html; charset = gb2312 'HTTP-equiv = 'content-type'/> ");
Out. println ("Out. println ("Out. println ("Out. println ();
Out. flush ();
Out. close ();
System. out. println (errNum + "," + errMsg );
}
}
Create an htdocs directory under the "e: \ workspace \ webserver" directory to store html files and other resources to be accessed. Then run the WebServer class and start the Web server program to access the server through a browser. In fact, reading is still very important, and many details are explained in the book. The above example is shown in the book published two years ago. I may not be able to understand it at the beginning, but after a long time, I will look back and see it...

Author: zha0ku1

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.