A simple Java Web server implementation, relatively simple, based on java.net.Socket and java.net.ServerSocket implementation;
First, the procedure executes the procedure
1. Create a ServerSocket object;
2. Call the Accept method of the ServerSocket object, wait for the connection, the connection succeeds will return a socket object, otherwise blocking waits all the time;
3. From the socket object to obtain InputStream and OutputStream byte stream, the two streams correspond to request requests and response responses respectively;
4. Processing request: Read InputStream Word throttling information, turn into a string form, and parse, here the resolution is relatively simple, just get the URI (Uniform Resource Identifier) information;
5. Processing response: According to the parsed URI information, from the Web_root directory to look for the requested resource file, read the resource file, and write it to the outputstream byte stream;
6. Close socket object;
7. Go to step 2 and continue to wait for the connection request;
Second, code implementation
Server implementation:
Package Ex01.pyrmont;
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; The public class Httpserver {/** * web_root is the directory where HTML and other files are stored. The web_root here is the Webroot directory under the working directory */public static final String WE
B_root = System.getproperty ("User.dir") + File.separator + "Webroot";
Close Service Command private static final String Shutdown_command = "/shutdown";
public static void Main (string[] args) {httpserver server = new Httpserver ();
Wait for connection request server.await ();
public void await () {ServerSocket serversocket = null;
int port = 8080;
try {//server socket Object ServerSocket = new ServerSocket (port, 1, Inetaddress.getbyname ("127.0.0.1"));
catch (IOException e) {e.printstacktrace ();
System.exit (1);
The//loop waits for a request while (true) {The socket socket = NULL;
InputStream input = null;
OutputStream output = null; try {//wait for connection, after successful connection, return a socket object socket = SERversocket.accept ();
input = Socket.getinputstream ();
Output = Socket.getoutputstream ();
Create the Request object and parse the request request = new request (input);
Request.parse ();
Check if the service command is turned off if (Request.geturi (). Equals (Shutdown_command)) {break;
///Create Response object Response Response = new Response (output);
Response.setrequest (Request);
Response.sendstaticresource ();
Closes the socket object Socket.close ();
catch (Exception e) {e.printstacktrace ();
Continue
}
}
}
}
Request class:
Package Ex01.pyrmont;
Import Java.io.InputStream;
Import java.io.IOException;
public class Request {private InputStream input;
Private String URI;
Public Request (InputStream input) {this.input = input;
Read request information from InputStream and get URI value public void Parse () {StringBuffer request = new StringBuffer (2048) from request;
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 ()); The/** * * requeststring form is as follows: * get/index.html http/1.1 * host:localhost:8080 * connection:keep-alive * Ontrol:max-age=0 * ... * This function is intended to get the/index.html string/private String Parseuri (string requeststring) {int index1, in
Dex2;
Index1 = Requeststring.indexof (");
if (index1!=-1) {index2 = Requeststring.indexof (', index1 + 1); if (Index2 > inDEX1) return requeststring.substring (index1 + 1, index2);
return null;
Public String GetURI () {return URI;
}
}
Response class:
Package Ex01.pyrmont;
Import Java.io.OutputStream;
Import java.io.IOException;
Import Java.io.FileInputStream;
Import Java.io.File; /* HTTP Response = status-line * (General-header | response-header | entity-header) CRLF) CRLF [Message-body] Sta Tus-line = http-version sp status-code SP reason-phrase CRLF/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 {//writes the WEB file to the OutputStream byte stream, File File = new file (Httpserver.web_root, Request.geturi ());
if (file.exists ()) {FIS = new FileInputStream (file);
int ch = fis.read (bytes, 0, buffer_size);
while (Ch!=-1) {output.write (bytes, 0, ch);
ch = fis.read (bytes, 0, buffer_size); }
}else {//File not found String errormessage = ' http/1.1 404 File Not found\r\n ' + ' content-type:text/html\r\n ' +
"content-length:23\r\n" + "\ r \ n" + "
Third, the result test
Access to existing resource files (note in the Webroot folder of the Engineering directory):
To access a resource file that does not exist:
To shut down the server:
Reference: "In-depth analysis of Tomcat"
@author the wind of the farmer
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.