1. knowledge point:
- Use Java to implement simple HTTP Server
- Use of serversocket and socket classes
- Use of the stringtokenizer class
- Multi-thread
2. Source Code:
ImportJava. Io. bufferedreader;
ImportJava. Io. fileinputstream;
ImportJava. Io. filenotfoundexception;
ImportJava. Io. ioexception;
ImportJava. Io. inputstream;
ImportJava. Io. inputstreamreader;
ImportJava. Io. outputstream;
ImportJava.net. serversocket;
ImportJava.net. Socket;
ImportJava. util. stringtokenizer;
Public ClassHttpserver {
Public Static VoidMain (string ARGs []) {
IntPort = 9090;
Serversocket server_socket;
Try{
// Listen to the server port and wait for the connection request
Server_socket =NewServersocket (port );
System. Out. println ("httpserver running on port" + server_socket.getlocalport ());
// Display the startup information
While(True ){
Socket socket = server_socket.accept ();
System. Out. println ("New Connection accepted" + socket. getinetaddress () + ":" + socket. getport ());
// Create sub-Thread
Try{
Httprequesthandler request =NewHttprequesthandler (socket );
Thread thread =NewThread (request );
// Start the thread
Thread. Start ();
}Catch(Exception e ){
System. Out. println (E );
}
}
}Catch(Ioexception e ){
System. Out. println (E );
}
}
}
ClassHttprequesthandlerImplementsRunnable {
Final StaticString CRLF = "\ r \ n ";
Socket socket;
Inputstream input;
Outputstream output;
Bufferedreader BR;
// Constructor
PublicHttprequesthandler (Socket socket)ThrowsException {
This. Socket = socket;
This. Input = socket. getinputstream ();
This. Output = socket. getoutputstream ();
This. BR =NewBufferedreader (NewInputstreamreader (socket. getinputstream ()));
}
// Run () method for implementing the runnable interface
Public VoidRun (){
Try{
Processrequest ();
}Catch(Exception e ){
System. Out. println (E );
}
}
Private VoidProcessrequest ()ThrowsException {
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 =NewStringtokenizer (headerline );
String temp = S. nexttoken ();
If(Temp. Equals ("get ")){
String filename = S. nexttoken ();
Filename = "." + filename;
// Open the requested file
Fileinputstream FCM = NULL;
BooleanFileexists = true;
Try{
Fiis =NewFileinputstream (filename );
}Catch(Filenotfoundexception e ){
Fileexists = false;
}
// Complete 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 200 OK" + CRLF;
Contenttypeline = "Content-Type:" + contenttype (filename) + CRLF;
Contentlengthline = "Content-Length:" + (NewINTEGER (FCM. Available (). tostring () + CRLF;
}Else{
Statusline = "HTTP/1.0 404 Not Found" + CRLF;
Contenttypeline = "text/html ";
Entitybody = "<HTML>" + "+ "Filename.html </body> }
// Send the message to the server
Output. Write (statusline. getbytes ());
Output. Write (serverline. getbytes ());
Output. Write (contenttypeline. getbytes ());
Output. Write (contentlengthline. getbytes ());
Output. Write (CRLF. getbytes ());
// Send information content
If(Fileexists ){
Sendbytes (FCM, output );
FCM. Close ();
}Else{
Output. Write (entitybody. getbytes ());
}
}
}
// Close the socket and stream
Try{
Output. Close ();
BR. Close ();
Socket. Close ();
}Catch(Exception e ){
}
}
Private Static VoidSendbytes (fileinputstream ISI, outputstream OS)ThrowsException {
// Create a 1 K buffer
Byte[] Buffer =New Byte[1024];
IntBytes = 0;
// Output the file to the socket output stream
While(Bytes = FS. Read (buffer ))! =-1 ){
OS. Write (buffer, 0, bytes );
}
}
Private StaticString contenttype (string filename ){
If(Filename. endswith (". htm") | filename. endswith (". html ")){
Return"Text/html ";
}
Return"FILENAME ";
}
}
Directory structure: place an HTML file under the project root directory
3. Test results:
Run the program, the server starts, open the browser, and enter the address:
Http: // localhost: 9090/1. html
Http: // localhost: 9090/2. html
Console output:
Publish via wiz