近日學習Java的網絡編程,看到一個及其簡單的例子,但是卻實現了一次Web訪問的功能,當然,於Tomcat和Weblogic等Web服務器自然是沒法比,可是展現了最基本的Web訪問的網絡原理的實現,短小精悍,看了才知道,原來還可以這樣。
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("<html>"); pw.println("<head>"); pw.println("<body>"); pw.println("This my page! You are welcome!"); pw.println("</body>"); pw.println("</head>"); pw.println("</html>"); 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(); } } }
編譯運行後,通過瀏覽器訪問http://localhost:8080/就可以了,是不是很神奇呢!