To better understand how a Web server, such as Tomcat, works, a Web server is now emulated with Java code:
1 ImportJava.io.*;2 Importjava.net.*;3 Public classMyWebServer4 {5 /*impersonate a Web server*/6 Public Static voidMain (string[] args)throwsException7 {8ServerSocket SS =NewServerSocket (9999);//occupies 9999 ports9 while(true){TenSocket s = ss.accept ();//Accept Request OneSystem.out.print ("9999 Port received request"); A //process the request and return the request result -OutputStream out =S.getoutputstream (); -BufferedReader br =NewBufferedReader (NewFileReader ("d:\\servlet-learnning\\hello.html")); theString line =NULL; - while((Line=br.readline ())! =NULL){ - Out.write (Line.getbytes ()); - } + br.close (); - out.close (); + } A } at}
Note: This code simulates a Web server that occupies a 9999 port and returns the d:\servlet-learnning\hello.html to the browser after it receives the request.
Compile and run this code, and then in the browser with http://localhost:9999 access to the emulated server, return the following results:
Note: The page displays the contents of the result as d:\servlet-learnning\hello.html
Java Simulation Web server code