欢迎来到天天文库
浏览记录
ID:39469779
大小:52.00 KB
页数:7页
时间:2019-07-04
《web代理服务器实验》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、Web代理服务器实验附录代码:1.ProxyCache类importjava.net.*;importjava.io.*;importjava.util.*;publicclassProxyCache{privatestaticHashMapURIBuff=newHashMap();///代理入口privatestaticintport;/*客户链接的套接字,port是要代理侦听来自客户端的传入连接的端口号*/privatestaticServerSocketsocket;/*创建一个Proxy对象和套接字*/publics
2、taticvoidinit(intp){port=p;try{socket=newServerSocket(port);}catch(IOExceptione){System.out.println("Errorcreatingsocket:"+e);System.exit(-1);}}publicstaticvoidhandle(Socketclient){Socketserver=null;HttpRequestrequest=null;HttpResponseresponse=null;//处理请求。如果存在异常,就回复并终止它。这意味着客户端将会挂起一段时间,直到超时.读取请
3、求try{BufferedReaderfromClient=newBufferedReader(newInputStreamReader(client.getInputStream()));request=newHttpRequest(fromClient);StringURI=request.URI;byte[]buff=URIBuff.get(URI);if(buff!=null){DataOutputStreamtoClient;/*创建一个toClient对象*/try{toClient=newDataOutputStream(client.getOutputStream()
4、);toClient.writeBytes(response.toString());toClient.write(buff);//缓存//写响应到客户端。首先头部,然后主体client.close();System.out.print("UseBuffered");}catch(IOExceptione){e.printStackTrace();}return;//不再往下走}}catch(IOExceptione){System.out.println("Errorreadingrequestfromclient:"+e);return;}//向服务器发送请求try{//打开套接
5、字并向其中写入请求server=newSocket(request.getHost(),request.getPort());DataOutputStreamtoServer=newDataOutputStream(server.getOutputStream());toServer.writeBytes(request.toString());//以下toServer不能够close,它关闭会导致连接server也会关闭//toServer.close();System.out.println("Requestforwarded.");}catch(UnknownHostExcep
6、tione){System.out.println("Unknownhost:"+request.getHost());System.out.println(e);return;}catch(IOExceptione){System.out.println("Errorwritingrequesttoserver:"+e);return;}//读取相应并将其转发给客户端try{DataInputStreamfromServer=newDataInputStream(server.getInputStream());response=newHttpResponse(fromServer
7、);DataOutputStreamtoClient=newDataOutputStream(client.getOutputStream());toClient.writeBytes(response.toString());URIBuff.put(request.URI,response.body);toClient.write(response.body);//写响应到客户端。首先头部,然后主体client.close();server.close(
此文档下载收益归作者所有