拦截浏览器发来请求,发送至tomcat,接收tomcat所发出的响应。
public static void main(String[] args) {
// TODO Auto-generated method stub
ServerSocket server;
try {
server = new ServerSocket(8088);
while(true)
{
Socket socket = server.accept();//等待客户机连接server,若连接则创建一套接字(会堵塞线程的继续执行)
InputStream in = socket.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
char[] chars = new char[1024];
int count = reader.read(chars);
System.out.println(new String(chars,0,count));
//与tomcat建立链接,形成一个代理服务器,发送请求至tomcat再获取tomcat的响应
Socket tomcat = new Socket("127.0.0.1",8080);
OutputStream out = tomcat.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write(chars,0,count);
writer.flush();
out.flush();
InputStream tomcatIn = tomcat.getInputStream();
InputStreamReader tomcatReader = new InputStreamReader(tomcatIn);
char[] tomcatChars = new char[2048];
count = tomcatReader.read(tomcatChars);
System.out.println(new String(tomcatChars,0,count));
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
网友评论