Applet用Http隧道技术和Servlet通讯 (源码)

红薯 发布于 2010/06/18 10:32
阅读 356
收藏 2

这是一个非常老的帖子,标注一下,以备不时之需。

客户端源码:

import java.io.*;
import java.applet.Applet;
import java.awt.*;

public class TestDataStreamApplet extends Applet
{
    String response;
    public  void  init(){     
      
      try{
         java.net.URL url = new java.net.URL(getDocumentBase(),"servlet/DataStreamEcho");         
         java.net.URLConnection con = url.openConnection(); 
         con.setUseCaches(true);
         con.setDoOutput(true);
         con.setDoInput(true);
         ByteArrayOutputStream byteout = new ByteArrayOutputStream();
         DataOutputStream out = new DataOutputStream(byteout);
         out.writeUTF("hello world!");
         out.flush();
         byte buf[] =  byteout.toByteArray();         
         con.setRequestProperty("Content-type","application/octest-stream");
         con.setRequestProperty("Content-length",""+buf.length);
         DataOutputStream dataout = new DataOutputStream(con.getOutputStream());
         dataout.write(buf);
         dataout.flush();
	 dataout.close();

         DataInputStream in = new DataInputStream(con.getInputStream());
         response = in.readUTF();
         System.out.println("read from server :" + response);
         in.close();  
      }
      catch(Exception e){
         e.printStackTrace();
      }
      
   }

   public void paint(Graphics g){
      g.drawString("read from server :" + response,10,20);
       
   }
}
服务器端源码:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class DataStreamEcho extends HttpServlet{
       public void service(HttpServletRequest req,HttpServletResponse resp)
           throws ServletException ,java.io.IOException
       {
           DataInputStream in = new DataInputStream(req.getInputStream());
           resp.setContentType("application/octest-stream");
           ByteArrayOutputStream byteout = new ByteArrayOutputStream();
           DataOutputStream out = new DataOutputStream(byteout);
           String response = in.readUTF();
           out.writeUTF(response);
           out.flush();
           byte buf[]= byteout.toByteArray();
           resp.setContentLength(buf.length);
           ServletOutputStream servletout = resp.getOutputStream();
           servletout.write(buf);
           servletout.close();  
       }
}

加载中
0
linan
linan

使用httpClient在客户端和服务器端传输对象  http://5linan.blog.163.com/blog/static/64903815200831105142141/ 

返回顶部
顶部