The first chapter a simple Web server
Httpserver.java
Package Com.simplehttpserver;import Java.net.socket;import Java.net.serversocket;import java.net.InetAddress; Import Java.io.inputstream;import java.io.outputstream;import Java.io.ioexception;import Java.io.File;public class Httpserver{public static final String web_root = System.getproperty ("User.dir") + File.separator + "webroot";//Close Httpser ver command private static final String Shutdown_command = "/shutdown";//Whether you receive the close Httpserver command private Boolean SHUTDOWN = False;pub Lic static void Main (string[] args) {httpserver server = new Httpserver (); server.await ();} public void await () {ServerSocket ServerSocket = null;int Port = 8080;try{serversocket = new ServerSocket (port, 1, InetAddr Ess.getbyname ("127.0.0.1"));} catch (IOException e) {e.printstacktrace (); System.exit (1);} Loop wait HTTP request while (!shutdown) {Socket socket = null;inputstream input = Null;outputstream output = Null;try{socket = Serve Rsocket.accept (); input = Socket.getinputstream (); output = Socket.getoutputstream ();//Create a Request object and parse the request reqUest = new Request (input); Request.parse ();//Create a Response object response response = new response (output); Response.setrequest (request); Response.sendstaticresource ();//close Socketsocket.close ();//check whether to close command shutdown = Request.geturi (). Equals (Shutdown_command);} catch (Exception e) {e.printstacktrace (); continue;}}}
Request.java
Package Com.simplehttpserver;import Java.io.inputstream;import Java.io.ioexception;public class Request{private InputStream input;private String uri;public Request (InputStream input) {this.input = input;} public void Parse () {StringBuffer request = new StringBuffer (2048); int i;byte[] buffer = new Byte[2048];try{i = Input.read ( buffer);} catch (IOException e) {e.printstacktrace (); i =-1;} for (int j = 0; J < i; J + +) {request.append ((char) buffer[j]);} System.out.print (Request.tostring ()); URI = Parseuri (request.tostring ());} private string Parseuri (string requeststring) {int index1, index2;index1 = Requeststring.indexof ("); if (index1! =-1) {in Dex2 = Requeststring.indexof (", index1 + 1), if (Index2 > Index1) return requeststring.substring (index1 + 1, index2);} return null;} Public String GetURI () {return URI;}}
Response.java
Package Com.simplehttpserver;import Java.io.outputstream;import Java.io.ioexception;import Java.io.FileInputStream ; Import Java.io.file;public class response{private static final int buffer_size = 1024; Request request;outputstream output;public Response (outputstream output) {this.output = output;} public void Setrequest (Request request) {this.request = Request;} public void Sendstaticresource () throws ioexception{byte[] bytes = new Byte[buffer_size]; FileInputStream FIS = null;try{file file = new file (Httpserver.web_root, Request.geturi ()); if (File.exists ()) {FIS = new Fi Leinputstream (file); int ch = fis.read (bytes, 0, Buffer_size), while (ch =-1) {output.write (bytes, 0, ch); ch = fis.read (byt ES, 0, buffer_size);}} Else{string errormessage = "http/1.1 404 File Not found\r\n" + "content-type:text/html\r\n" + "content-length:23\r\n" + "\ r \ n" + "
(1) System.getproperty ("User.dir") is to get the current working directory
public static final String Web_root defined in Httpserver is the working directory/webroot
(2) When creating a TCP server Listener
Try {serversocket = new ServerSocket (port, 1, Inetaddress.getbyname ("127.0.0.1")); } catch (IOException e) {e.printstacktrace (); System.exit (1); }
The program actively captures the IOException, in-depth serversocket source can see:
public ServerSocket (int port, int backlog, inetaddress bindaddr) throws IOException { setimpl (); if (Port < 0 | | port > 0xFFFF) throw new IllegalArgumentException ( "Port value out of range:" + port); if (Backlog < 1) backlog =; try { bind (new Inetsocketaddress (BINDADDR, Port), backlog), } catch (SecurityException e) { close (); throw e; } catch (IOException e) { close (); throw e; } }
Three exceptions may be thrown when creating a ServerSocket object (enabling TCP server-side snooping)
(1) New illegalargumentexception in the TCP port range to be monitored is not in the correct range 0-65535, the throw parameter exception when the exception RuntimeException not explicitly after the method throws and the method call at the try Catch
(2) SecurityException is also a runtimeexception exception trigger condition If the security manager exists and its checkListen
methods do not allow the operation.
(3) IOException is a non-runtime exception if an I/O error occurs when the socket is opened.
A brief introduction to the following serversocket:
Bind the server socket to a specific port number so that the remote client can locate the TCP service and use any free port if the value passed in is 0 (zero)-but the client may not be able to access the service, unless the client port number is notified in any way. Allocate enough space for the queue to support a specific number of client sockets. In the overloaded version of the serversocket (int port, int numberofclients) constructor, the inetaddress parameter is added to the Dodi, which allows the server socket to bind to a specific IP address. For example, a computer might have two network cards, or use a virtual IP address to configure it to work like a few computers. If the value of the address is empty (NULL), the server socket will accept the request at all local addresses. By default, the queue size is set to 50, but an alternate constructor is provided, which allows you to modify this setting. An exception occurs if the port is already bound, or if the security constraints (such as security rules or operating system constraints on well-known ports) block access.
Deep anatomy of Tomcat read (i)