Tomcat、Weblogic、Jetty、WebService做了什么样子的事情呢?只不过是通过SOCKET来监听服务器上某一个端口的请求,进行请求的处理,并且将响应信息写回去。简单的说就是这样了,但是复杂里面讲呢,Tomcat必须要兼顾安全、标准、完美兼容HTTP的规范、多线程支持、数据库,数据源支持、可配置、Web端管理、SSL等等方面,所以又是非常复杂的。下面是一个例子,对于新手而言是非常有用的一段代码。
package com.ziwen.container; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class AppServer { public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(8080); Socket socket =serverSocket.accept(); InputStream inputStream = socket.getInputStream(); byte[] msgBytes = new byte[1024]; int len = inputStream.read(msgBytes); String msg = new String(msgBytes,0,len); System.out.println(msg); OutputStream outputStream = socket.getOutputStream(); PrintWriter printWriter = new PrintWriter(outputStream,true); printWriter.println("successful!"); socket.close(); serverSocket.close(); } }
A useful demo.