I recently learned Java Network Programming and saw a simple example, but implemented a Web access function. Of course, it cannot be compared with Web servers such as Tomcat and Weblogic, however, it shows the implementation of the most basic Web access network principle, which is short and concise. You can see it after reading it.
Import java. io. IOException;
Import java. io. OutputStream;
Import java. io. PrintWriter;
Import java.net. Socket;
Public class HTTPThread implements Runnable {
Private Socket socket;
Private int count;
Public HTTPThread (){
}
Public HTTPThread (Socket socket, int count ){
This. socket = socket;
This. count = count;
}
@ Override
Public void run (){
// TODO Auto-generated method stub
Try {
OutputStream OS = socket. getOutputStream ();
PrintWriter pw = new PrintWriter (OS );
Pw. println ("Pw. println ("Pw. println ("<body> ");
Pw. println ("This my page! You are welcome! ");
Pw. println ("</body> ");
Pw. println ("Pw. println ("
Pw. flush ();
Pw. close ();
OS. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
Import java. io. IOException;
Import java.net. ServerSocket;
Import java.net. Socket;
Public class TCPServer {
Public static void main (String [] args ){
Int count = 1;
Try {
ServerSocket ss = new ServerSocket (8080 );
Socket s = null;
While (s = ss. accept ())! = Null ){
System. out. println ("The visitor:" + count );
HTTPThread httpThread = new HTTPThread (s, count );
Thread thread = new Thread (httpThread );
Thread. start ();
Count ++;
}
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
After compilation and running, you can access http: // localhost: 8080/through a browser. Isn't that amazing!
Recommended reading:
Apache-multi-site log analysis
Install Apache that supports SSL in Ubuntu 13.10
Disguise Apache to prevent Web Server intrusion
Compiling and installing the Apache Python module mod_wsgi
Enterprise Shell script analysis and Apache Log cutting practices
Linux website architecture series-Apache-deployment