近日学习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/就可以了,是不是很神奇呢!