Java network programming: Using Java to implement a Web server

Source: Internet
Author: User
Tags final implement socket split thread java web microsoft frontpage port number
Web|web Service |web Server | programming | Network Hypertext Transfer Protocol (HTTP) is the application layer in TCP/IP protocol, is the most widely known protocol, is also one of the most core protocols in the interconnection network, the same, HTTP is based on C/s or B/E model implementation. In fact, the browsers we use, such as Netscape or IE, are the clients that implement the HTTP protocol, and some common Web server software such as Apache, IIS, and iplanet Web servers are the servers in the HTTP protocol. Web pages are positioned by server resources and transmitted to browsers, which are interpreted by the browser and are seen by customers.

The work of the Web is based on the client/server computing model, consisting of a Web browser (client) and a Web server (server), which communicates with a Hypertext Transfer Protocol (HTTP). The HTTP protocol is an application layer protocol between Web browsers and Web servers, and is a universal, stateless, object-oriented protocol.

A complete HTTP protocol session process consists of four steps:

Connection, the Web browser establishes a connection to the Web server, and opens a virtual file called a socket (socket), which marks the successful connection establishment;

Request, the Web browser submits the request to the Web server via the socket. HTTP requests are typically a GET or post command (post is used for a form parameter pass);

Answer, the Web browser submits the request and passes it through the HTTP protocol to the Web server. When the Web server receives the transaction, the processing results are returned to the Web browser via HTTP, thus displaying the requested page in the Web browser;

Close the connection and the Web browser must disconnect from the Web server to ensure that other Web browsers can connect to the Web server after the answer is complete.



Programming Java to implement Web server function


Programming Ideas

Based on the session process of the HTTP protocol above, the method for implementing the Web server program for GET requests in this example is as follows:

By creating the ServerSocket class object, listens for the user-specified port (8080), waits for and accepts the client request to the port. Creates an input stream and an output stream associated with the socket, and then reads the client's request information. If the request type is get, the access HTML file name is obtained from the request information, and if the HTML file exists, the HTML file is opened, the HTTP header information and the contents of the HTML file are passed back to the Web browser via the socket, and the file is closed, otherwise the error message is sent to the Web browser Finally, close the socket that is connected to the appropriate Web browser.

The source code for writing Web server Httpserver.java files in Java is as follows:

Httpserver.java
Import java.net.*;
Import java.io.*;
Import java.util.*;
Import java.lang.*;
public class httpserver{
public static void Main (String args[]) {
int port;
ServerSocket Server_socket;
Read Server port number
try {
Port = Integer.parseint (Args[0]);
}
catch (Exception e) {
Port = 8080;
}
try {
Listens on server ports, waits for connection requests
Server_socket = new ServerSocket (port);
System.out.println ("Httpserver running on port" +
Server_socket.getlocalport ());
Show startup information
while (true) {
Socket socket = server_socket.accept ();
SYSTEM.OUT.PRINTLN ("New Connection accepted" +
Socket.getinetaddress () +
":" + socket.getport ());
Create a split-thread
try {
Httprequesthandler request =
New Httprequesthandler (socket);
Thread thread = new thread (request);
Start thread
Thread.Start ();
}
catch (Exception e) {
System.out.println (e);
}
}
}
catch (IOException e) {
System.out.println (e);
}
}
}
Class Httprequesthandler implements Runnable
{
Final static String CRLF = "\ r \ n";
Socket socket;
InputStream input;
OutputStream output;
BufferedReader BR;
Construction method
Public Httprequesthandler (socket socket) throws Exception
{
This.socket = socket;
This.input = Socket.getinputstream ();
This.output = Socket.getoutputstream ();
this.br =
New BufferedReader (New InputStreamReader (Socket.getinputstream ()));
}
Implementing the Run () method of the Runnable interface
public void Run ()
{
try {
ProcessRequest ();
}
catch (Exception e) {
System.out.println (e);
}
}
private void ProcessRequest () throws Exception
{
while (true) {
Read and display the request information submitted by the Web browser
String headerline = Br.readline ();
SYSTEM.OUT.PRINTLN ("The client request is" +headerline);
if (headerline.equals (CRLF) | | | headerline.equals ("")) break;
StringTokenizer s = new StringTokenizer (headerline);
String temp = S.nexttoken ();
if (Temp.equals ("get")) {
String fileName = S.nexttoken ();
filename = "." + filename;
Open the requested file
FileInputStream FIS = null;
Boolean fileexists = true;
Try
{
FIS = new FileInputStream (fileName);
}
catch (FileNotFoundException e)
{
FileExists = false;
}
Complete the response message
String serverline = "Server:a simple java Httpserver";
String statusline = null;
String contenttypeline = null;
String entitybody = null;
String contentlengthline = "error";
if (fileexists)
{
Statusline = "http/1.0 OK" + CRLF;
Contenttypeline = "Content-type:" +
ContentType (fileName) + CRLF;
Contentlengthline = "Content-length:"
+ (New Integer (Fis.available ()). ToString ()
+ CRLF;
}
Else
{
Statusline = "http/1.0 404 Not Found" + CRLF;
Contenttypeline = "text/html";
Entitybody = "<HTML>" +
""<body>404 not Found"
+ "<br>usage:http://yourhostname:port/"
+ "filename.html</body>}
Send to server information
Output.write (Statusline.getbytes ());
Output.write (Serverline.getbytes ());
Output.write (Contenttypeline.getbytes ());
Output.write (Contentlengthline.getbytes ());
Output.write (Crlf.getbytes ());
Send Message Content
if (fileexists)
{
Sendbytes (FIS, Output);
Fis.close ();
}
Else
{
Output.write (Entitybody.getbytes ());
}
}
}
Close sockets and streams
try {
Output.close ();
Br.close ();
Socket.close ();
}
catch (Exception e) {}
}
private static void Sendbytes (FileInputStream fis, OutputStream os)
Throws Exception
{
Create a 1K buffer
byte[] buffer = new byte[1024];
int bytes = 0;
Output the file to the socket output stream
while ((bytes = fis.read (buffer))!=-1)
{
Os.write (buffer, 0, bytes);
}
}
private static string ContentType (String fileName)
{
if (Filename.endswith (". htm") | | filename.endswith (". html")
{
return "text/html";
}

return "FileName";
}
}



Programming Skills Description

Main thread Design

The main thread is designed in the main thread Httpserver class to implement the server port listening, the server to accept a client request to create a thread instance processing request, the code is as follows:

Import java.net.*;
Import java.io.*;
Import java.util.*;
Import java.lang.*;
public class httpserver{
public static void Main (String args[]) {
Port
ServerSocket Server_socket;
Read Server port number
try {
Port = Integer.parseint (Args[0]);
}
catch (Exception e) {
Port = 8080;
}
try {
Listens on server ports, waits for connection requests
Server_socket = new ServerSocket (port);
System.out.println ("Httpserver running on port"
+server_socket.getlocalport ());
..........
..........



Thread Design for connection processing

The HTTP protocol is processed in the threaded Httprequesthandler class, which implements the Runnable interface, and the code is as follows:

Class Httprequesthandler implements Runnable
{
Final static String CRLF = "\ r \ n";
Socket socket;
InputStream input;
OutputStream output;
BufferedReader BR;
Construction method
Public Httprequesthandler (socket socket) throws Exception
{
This.socket = socket;
Get input and output stream
This.input = Socket.getinputstream ();
This.output = Socket.getoutputstream ();
this.br =
New BufferedReader (New InputStreamReader (Socket.getinputstream ()));
}

Implementing the Run () method of the Runnable interface
public void Run ()
{
try {
ProcessRequest ();
}
catch (Exception e) {
System.out.println (e);
}
}



Build the ProcessRequest () method to handle the receiving and sending of information

As the main content of implementing the Runnable interface, call the ProcessRequest () method in the Run () method to handle the receipt of the customer request content and the sending of the server return information as follows:

private void ProcessRequest () throws Exception
{
while (true) {
Read and display the request information submitted by the Web browser
String headerline = Br.readline ();
SYSTEM.OUT.PRINTLN ("The client request is" + headerline);
if (headerline.equals (CRLF) | | | headerline.equals ("")) break;
Split a customer request based on a space in the request string
StringTokenizer s = new StringTokenizer (headerline);
String temp = S.nexttoken ();
if (Temp.equals ("get")) {
String fileName = S.nexttoken ();
filename = "." + filename;
.............
.............



After obtaining a client request in the ProcessRequest () method, a StringTokenizer class is used to complete the split of the string, which implements the ability to split the string into strings based on the delimiter specified in the string (the default is a space). Using the Nexttoken () method to get these strings, the Sendbytes () method completes the sending of the information content, and the ContentType () method is used to judge the type of the file.

Show Web pages

The index.html file code that displays the Web page is as follows:

<meta http-equiv= "Content-language" content= "ZH-CN" >
<meta name= "generator" content= "Microsoft FrontPage 5.0" >
<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 ">
<title>java Web Server </title>
<body>
<p>********* <font color= "#FF0000" > Welcome to your arrival! </font>*********</p>
<p> This is a WEB server implemented in the Java language </p>
</body>




Run instance


In order to test the correctness of the above program, the compiled Httpserver.class, Httprequesthandler.class and index.html files are placed in the same directory of a host on the network.

First run the server program Java httpserver 8080, the server program after the run shows the port information "Httpserver runing on port 8080", and then in the browser's address bar input http://localhost:8080/ index.html, the Web page is displayed correctly, and some information appears on the server in the "Httpserver runing on port 8080" window.

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.