TCP通信模型创建一个Web服务器
IIS、Apache、Tomcat等Web服务器都是采用TCP通信模型的,介绍一种TCP编程API创建一个简易的Web服务器。
public void main(String [] args){ ServerSocket ss=new ServerSocket(8080); Socket s=null; while((s=ss.accept())!=null){ new HttpThread(s).start(); } ss.close(); } class HttpThread extends Thread{ private Socket socket; public HttpThread(Socket socket){ super(); this.socket=socket; } public void run(){ try{ OutputStream os=socket.getOutputStream(); PrintWriter pw=new PrintWrite(os); pw.println("<html>"); pw.println("<body>"); pw.println("hello"); pw.println("</body>"); pw.println("</html>"); pw.flush(); pw.close(); socket.close(); }catch(IOException e){ } } }
运行以上程序后通过浏览器输入localhost:8080就能得到Web服务器的内容。

浙公网安备 33010602011771号