Java-based web server work mechanism (1)

zhaozj2021-02-16  45

Java-based web server work mechanism (1)

A web server is also known as an HTTP server because it communicates with its clients and its customers, and these customers are usually browser. A Java-based web server uses two important classes: java.net.socket and java.net.serversocket, and communicate via HTTP messages. The beginning of this article will discuss HTTP and these two classes, followed, will explain the working mechanism of a simple web server application.

Hypertext Transfer Protocol (HTTP)

The HTTP protocol allows the server and client to receive and transmit data over the Internet. It is a request and response protocol ---- Client Send Request, the server responds to the request. HTTP uses a reliable TCP connection, the default TCP port is 80. The first edition of HTTP is HTTP / 0.9 and then replaced by HTTP / 1.0. The current latest version is HTTP / 1.1, which is defined in the RPC2616 specification document.

This chapter is simple to explain HTTP 1.1, which is still enough for the message sent by the web server application. If you are very interested, you can refer to RFC 2616 documentation.

With HTTP, the client initializes a transaction session by establishing a connection and sending an HTTP request, the server contacts the client or responds to a callback connection to the client. They can be interrupted. For example, when using a web browser, you can stop the file download process on the browser to stop the file download process, and turn off the HTTP connection with this web server.

HTTP request (Requests)

An HTTP Request contains three parts:

Method, URL, Agreement / Version request Baotou Request Headers entity package (Entity Body)

The example gives an example of an HTTP request:

Post / Servlet/default.jsp HTTP / 1.1

Accept: Text / Plain; Text / HTML

Accept-language: EN-GB

Connection: Keep-alive

Host: Localhost

Referr: http://localhost/ch8/senddetails.htm

User-agent: mozilla / 4.0 (compatible; msie 4.01; windows 98)

Content-Length: 33

Content-Type: Application / X-WWW-FORM-URLENCODED

Accept-encoding: Gzip, deflate

Lastname = franks & firstname = michael

The first line of request is Method-Uri-Protocol / Version.

Post / Servlet/default.jsp HTTP / 1.1

The request is the POST method, the later / Servlet/default.jsp represents a URL address, and HTTP / 1.1 represents the version of the protocol.

The HTTP standard specification defines some request methods to use to give each HTTP request. HTTP 1.1 Support 7 Request: GET, POST, HEAD, OPTIONS, PUT, DELETE, and TRACE. GET and POST are the most common ways in Internet applications.

The URI completely specifically indicated an Internet resource. A URI is usually interpreted relative to the root directory of the server. Therefore, it always uses the symbol (/). A URL is actually a URI type. The protocol version represents the version of the HTTP protocol currently being used.

Request Header requests some useful client environments and entity (entity body) information. For example, it can include the length of the language and entity used by the browser. Each request header is separated by the CRLF (Route) sequence. In the previous HTTP request, the entity is a simple line below:

Lastname = franks & firstname = michael

In a typical HTTP request, this entity can easily become longer.

HTTP response (responses)

Similar to the request, an HTTP response also contains three parts:

Protocol-Status Code-Description Responds to the Response Headers entity (Entity Body)

Below is a simple example of HTTP response:

HTTP / 1.1 200 ok

Server: Microsoft-IIS / 4.0

Date: Mon, 3 Jan 1998 13:13:33 GMT

Content-Type: Text / HTML

Last-Modified: Mon, 11 Jan 1998 13:23:42 GMT

Content-Length: 112

http response example </ title> </ head> <body></p> <p>Welcome to Brainy Software</p> <p></ body></p> <p></ html></p> <p>The first line of response to the header and the request of the above request are similar. The first line tells us that the agreement is HTTP1.1, and the response request has been successful (200 means success), everything is OK.</p> <p>In response to the header and the requesting header, some useful information is also included. The response entity is the content of the HTML. The head and entities are also separated by the CRLF sequence.</p> <p>Socket class</p> <p>Sockets are an endpoint for a network connection. It enables the application to read and write through the network. By sending and receiving byte streams on the connection, two software programs located in different computers can communicate with each other. In order to send a message to another, you need to know the IP address of the other machine and the socket port number. In Java, a socket is represented by the java.net.socket class.</p> <p>In order to create a socket, you can use the Socket class constructor to complete. These constructors accept host names and ports:</p> <p>Public socket (String Host, Int Port)</p> <p>Host represents a remote computer name or an IP address, Port represents the port number of the remote application. For example, to connect to Yahoo.com at the 80-port, you need to construct the following Socket:</p> <p>New Socket ("Yahoo.com", 80);</p> <p>Once you have successfully created an instance of a Socket class, you can use it to send and accept bytes. To send byte streams, you must first call the GetputStream method of the Socket class to get a java.io.outputstream object. To send a text to a remote application, you often construct a java.io.PrintWriter object returned from the OutputStream object. To receive the byte stream connected to the other end, to call the GetInputStream method of the Socket class, the method is returned from java.io.inputstream.</p> <p>The following block creates a socket, communicating with the local HTTP server (127.0.0.1 representative local), send an HTTP request, and then receives a response from the server. It creates a StringBuffer to save the response and print it to the console. Socket Socket = New Socket ("127.0.0.1", "8080");</p> <p>OutputStream OS = Socket.getOutputStream ();</p> <p>Boolean Autoflush = True;</p> <p>PrintWriter Out = New PrintWriter (socket.getOutputStream (), Autoflush;</p> <p>BufferedReader in = New BufferedReader</p> <p>New INPUTSTREAMREADER (Socket.getInputStream ()));</p> <p>// send an HTTP Request to the Web Server</p> <p>Out.println ("Get /Index.jsp HTTP / 1.1");</p> <p>Out.println ("Host: Localhost: 8080);</p> <p>OUT.PRINTLN ("Connection: Close");</p> <p>Out.println ();</p> <p>// read the response</p> <p>Boolean loop = True;</p> <p>StringBuffer SB = New StringBuffer (8096);</p> <p>While (loop) {</p> <p>IF (in.ready ()) {</p> <p>INT i = 0;</p> <p>While (i! = - 1) {</p> <p>i = in.read ();</p> <p>Sb.Append ((char) i);</p> <p>}</p> <p>Loop = false;</p> <p>}</p> <p>Thread.currentthread (). SLEEP (50);</p> <p>}</p> <p>// Display the response to the out concele</p> <p>System.out.println (sb.toString ());</p> <p>Socket.close ();</p> <p>To get an exact response from the server, you need to send an HTTP request to follow the HTTP protocol rule. If you read the above "Hypertext Transfer Protocol (HTTP)", you should be able to understand the code that just establishes Socket above.</p> <p>Translated by Willpower, 2003.11.23</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-24927.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="24927" 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.045</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 = 'c8O4lNPiKdmtnaF5nuKf72oexj8fEYvLl37ad_2BaWsSXxZ0pJXNgteKPbgKgc61WEIekV3e0REhCtMXNH'; 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>