java与浏览器对话小实验.docVIP

  • 4
  • 0
  • 约2千字
  • 约 2页
  • 2017-05-16 发布于湖南
  • 举报
java与浏览器对话小实验

实验介绍: 在Java与tomcat对话小实验中,我们给tomcat发送了请求报文,并接收了回应报文显示在界面上。现在,我们要写另外一个程序,监听浏览器的请求,把浏览器发过来的请求进行解析,得到浏览器所要访问的文件,把文件内容再组合成报文发回去给浏览器显示。最终,我们完成了两个工程,一个是SimpleViewer,一个是SimpleServer,这两个程序实现了三个目的:1、SimpleViewer可以和tomcat之间以http消息通信,传递数据。2、SimpleServer可以和IE,Firefox等浏览器之间以http消息通信,传递数据。3、SimpleViewer可以和SimpleServer之间以http消息通信并传递数据。访问SimpleServer上资源的时候,url形如:http://localhost:8888/source/helloworld.html,source为工程目录下面的文件夹,hellocworld.html则为请求的页面文件。 关键代码: private static Document doc = null; static{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.parse(MimeConfig.xml); } Dom方式解析xml的三步,1、创建DocumentBuilderFactory 2、创建DocumentBuilder 3、解析xml文件得到Document对象。得到Document对象后,就可以通过dom中的方法得到其它结点。写在静态块儿中的好处是只解析一次。 private ServerSocket srvSck = null; public void listening() { try { srvSck = new ServerSocket(8888); while (true) { //阻塞等待客户端连接 Socket socket = srvSck.accept(); //客户端连接上后开辟新线程与客户端保持TCP连接 new AccessThread(socket).start(); } } catch (IOException e) { e.printStackTrace(); } } 创建ServerSocket监听客户端连接,一但有客户端连上,马上开辟一个新的线程,用这个新线程与客户端保持TCP连接。此处的8888端口号写死,则客户端只能访问8888端口,真正使用时,最好写入xml文件中,从文件中读出端口号会增加程序的灵活性。 StringBuilder response = new StringBuilder(); //如果没有在xml中找到对应的mime类型,提示不支持该类型 if (mimeType == null) { //组装http回应报文 response.append(HTTP/1.1 200 OK Date: + new Date() + \r\n); response.append(Server: SimpleServer/1.0\r\n); response.append(Connection: close\r\n); response.append(Content-Type: text/html\r\n); response.append(\r\n); response.append(html\r\nhead\r\ntitleerror/title\r\n/head\r\nbody不支持的文件格式!/body\r\n/html); response.append(\r\n); 判断mime类型是否在配置文件中配置,如没有,则返回“不支持的文件格式信息”,该信息同样以http报文的形式返回,其中,切记每一行末尾要加上\r\n,http头和数据内容间要有一个空行。 StringBuffer requestBuffer = new StringBuffer(); String line = ; //循环读出输入流中的值 while ((line = in.readLine()).length() != 0) { requestBuffer.append(line + \r\n); } 示例工程: ----------------------------精品word文档 值得下载 值得拥有-------------

文档评论(0)

1亿VIP精品文档

相关文档