[Reserved] Implement a web server with Java

xiaoxiao2021-03-06  114

Hypertext Transfer Protocol (HTTP) is an application layer in TCP / IP protocol, which is the most widely known protocol, which is also one of the most core protocols in the interconnect. Similarly, HTTP is also implemented based on C / S or B / S model. In fact, our browser such as Netscape or IE is a client in the HTTP protocol, and some common web server software such as Apache, IIS, and IPlanet Web Server are server-only in the HTTP protocol. The web page is positioned by the server resource, transferred to the browser. After the browser explains, it is seen by the customer.

The WEB's work is based on the client / server computing model, consisting of a web browser (client), and web server (server), and the Hypertext Transfer Protocol (HTTP) is communicated between the two. The HTTP protocol is an application layer protocol between web browsers and web servers, which is a general, stateless, object-oriented protocol.

A complete HTTP protocol session process includes four steps:

◆ Connection, the web browser establishes a connection to the web server, open a virtual file called Socket (socket), and the establishment of this file is successful;

◆ Request, the web browser submits a request to the web server via Socket. HTTP's request is typically a get or post command (POST is used for the transfer of the FORM parameter);

◆ Acknowledges that the web browser submits the request, transferred to the web server via the HTTP protocol. After the web server is connected, transaction processing, the processing result is sent back to the web browser via HTTP, so that the requested page is displayed on the web browser;

◆ Close the connection, the web browser and the web server must be disconnected after the response is completed to ensure that other web browsers can connect with the web server.

Programming ideas

According to the session process of the above HTTP protocol, the method of implementing the web server program of the GET request is implemented, and the method is as follows:

By creating a Serversocket class object, listen to the port (8080) specified by the user, wait and accept the client request to the port. Create the input stream and output stream associated with the socket, and then read the client's request information. If the request type is Get, get the HTML file name accessed from the request information; if the HTML file exists, open the HTML file, transfer the HTTP header information and the HTML file content to the web browser via Socket, then close the file, then close the file, Otherwise send an error message to the web browser. Finally close the socket connected to the corresponding web browser.

Write the source code of the web server httpserver.java file with Java as follows:

//httpserver.java

Import java.net. *;

Import java.io. *;

Import java.util. *;

Import java.lang. *;

Public clas 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 {

// listen to the server port, wait for the connection request

Server_socket = new serversocket (port);

System.out.println ("Httpserver Running on Port" Server_Socket.getlocalPort ());

// Display startup information

While (true) {

Socket Socket = Server_Socket.accept ();

System.out.println ("New Connection ACCEPTED"

Socket.getinetaddress ()

":" Socket.getPort ());

// Create a division thread

Try {

HttpRequestHandler Request =

New httprequesthandler (socket);

Thread thread = new three (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 input.getinputstream ()));

}

/ / Realize 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 contentthline = "error";

IF (FileExists)

{

StatusLine = "HTTP / 1.0 200 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 = ""

" 404 not true> </ head>" </p> <p>"<Body> 404 not found"</p> <p> "<br> USAGE: http:// YourHostname: Port /"</p> <p> "Filename.html </ body> </ html>";</p> <p>}</p> <p>// Send to server information</p> <p>Output.write (statusline.getbytes ());</p> <p>Output.write (ServerLine.getBytes ());</p> <p>Output.write (ContentTyPeline.getbytes ());</p> <p>Output.write (ContentLengthline.getBytes ());</p> <p>Output.write (crlf.getbytes ());</p> <p>// Send information content</p> <p>IF (FileExists)</p> <p>{</p> <p>SendBytes (Fis, Output);</p> <p>fis.close ();</p> <p>}</p> <p>Else</p> <p>{</p> <p>Output.write (EntityBody.getbytes);</p> <p>}</p> <p>}</p> <p>}</p> <p>// Close the socket and stream</p> <p>Try {</p> <p>Output.close ();</p> <p>br.close ();</p> <p>Socket.close ();</p> <p>}</p> <p>Catch (Exception E) {}</p> <p>}</p> <p>Private Static Void Sendbytes (FileInputStream Fis, OutputStream OS)</p> <p>Throws Exception</p> <p>{</p> <p>// Create a 1K buffer</p> <p>Byte [] buffer = new byte [1024];</p> <p>INT BYTES = 0;</p> <p>// output the file to the socket output stream</p> <p>While ((Bytes = fis.read (buffer))! = -1)</p> <p>{</p> <p>Os.write (buffer, 0, bytes);</p> <p>}</p> <p>Private static string contenttype (String filename)</p> <p>{</p> <p>IF (Filename.endSwith) || filename.endswith (". html")))</p> <p>{</p> <p>Return "Text / HTML";</p> <p>}</p> <p>Return "filename";</p> <p>}</p> <p>}</p> <p>Programming skills</p> <p>◆ Main thread design</p> <p>The main thread is designed to implement the server port listener in the main thread httpserver class, and the server creates a thread instance processing request after accepting a client request. The code is as follows:</p> <p>Import java.net. *;</p> <p>Import java.io. *;</p> <p>Import java.util. *;</p> <p>Import java.lang. *;</p> <p>Public clas httpserver {</p> <p>Public static void main (string args []) {</p> <p>Port;</p> <p>Serversocket Server_Socket;</p> <p>// Read server port number</p> <p>Try {</p> <p>Port = integer.parseint (args [0]);</p> <p>}</p> <p>Catch (Exception E) {</p> <p>Port = 8080;</p> <p>}</p> <p>Try {</p> <p>// listen to the server port, wait for the connection request</p> <p>Server_socket = new serversocket (port);</p> <p>System.out.println ("Httpserver Running on Port"</p> <p> Server_Socket.getlocalPort ());</p> <p>........</p> <p>........</p> <p>◆ Connection processing points thread design</p> <p>The HTTP protocol is implemented in the httpRequestHandler class, which implements the runnable interface, the code is as follows:</p> <p>Class HttpRequestHandler Implements Runnable</p> <p>{</p> <p>Final static string crlf = "/ r / n";</p> <p>Socket socket;</p> <p>InputStream INPUT;</p> <p>OutputStream output;</p> <p>BUFFEREDReader Br;</p> <p>// Construction method</p> <p>Public HttpRequestHandler (Socket Socket) Throws Exception</p> <p>{</p> <p>This.socket = Socket;</p> <p>// Get input and output flow</p> <p>This.input = Socket.getinputStream ();</p> <p>this.output = socket.getOutputStream ();</p> <p>THIS.BR =</p> <p>New BufferedReader (new input.getinputstream ()));</p> <p>}</p> <p>/ / Realize the Run () method of the runnable interface</p> <p>Public void Run ()</p> <p>{</p> <p>Try {</p> <p>PROCESSREQUEST ();</p> <p>}</p> <p>Catch (Exception E) {</p> <p>System.out.println (e);</p> <p>}</p> <p>}</p> <p>◆ Build a processRequest () method to process information reception and send</p> <p>As the main content of the RunNable interface, the processRequest () method is called in the run () method to handle the reception of the customer request content and the sender of the server returns information, the code is as follows:</p> <p>Private Void ProcessRequest () THROWS Exception</p> <p>{</p> <p>While (true) {</p> <p>/ / Read and display the request information submitted by the web browser</p> <p>String headerline = br.readline (); System.out.println ("The Client Request IS" HeaderLine;</p> <p>IF (HeaderLine.equals (CRLF) || HeaderLine.equals (")) Break;</p> <p>/ / Split the customer request according to the space in the request string</p> <p>StringTokenizer S = New StringTokenizer (HeaderLine);</p> <p>String Temp = S.NEXTTOKEN ();</p> <p>IF (Temp.equals ("Get")) {</p> <p>String filename = S.NEXTTOKEN ();</p> <p>Filename = "." filename;</p> <p>...........</p> <p>...........</p> <p>After obtaining the client request in the ProcessRequest () method, complete the splitting of the string using a StringTokenizer class, which can achieve a string into a string according to the separator (default space) specified in the string. Function. These strings are sequentially obtained by using the nexttoken () method; the sendbytes () method completes the sending of the information content, and the contentType () method is used to determine the type of file.</p> <p>Display web page</p> <p>The INDEX.html file code that displays the web page is as follows:</p> <p><Html></p> <p><HEAD></p> <p><Meta http-equiv = "content-language" content = "zh-cn"></p> <p><Meta name = "generator" content = "Microsoft FrontPage 5.0"></p> <p><Meta http-equiv = "content-type" content = "text / html; charSet = GB2312"></p> <p><Title> Java Web Server </ Title></p> <p></ HEAD></p> <p><Body></p> <p><P> ********* <font color = "# ff0000"> Welcome you! </ Font> ********* </ p></p> <p><P> This is a web server that implements Java language </ p></p> <p><Hr></p> <p></ Body></p> <p></ Html></p> <p>Running instance</p> <p>In order to test the correctness of the above program, the compiled httpserver.class, httprequesthandler.class, and the INDEX.html file above the network are placed in the same directory of a host of the network.</p> <p>First run the server program Java Httpserver 8080, the server program "httpserver running on port 8080" is displayed, and then enters http: // localhost: 8080 / index.html in the browser's address bar, you can display the web page correctly. At the same time, some information will appear in the "HTTPServer Runing On Port 8080" window.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-98228.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="98228" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.041</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'LBVD6tfmpd1PBqAPqtA1EcmNmVHWAIfFww3Rg5qtbeYG6PCoJ_2BdTIybKyHqGVvLaqWDiKPTpund3cNwn'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>