往服务器端发送消息并接收返回的消息--输入输出流应用

用输入输出流实现往服务器端发送消息并接收返回的消息。

 

客户端 StreamTest.java:

 

public class StreamTest implements Controller{
 
 public ModelAndView handleRequest(HttpServletRequest req,
   HttpServletResponse res) throws Exception {

 

URL url = new URL("http://localhost:8088/Test/streamtestserver.do ");
  HttpURLConnection con = (HttpURLConnection)url.openConnection();
        con.setRequestMethod("POST"); // 设置请求方式
        con.setRequestProperty("Content-Type", "application/stream"); // 设置请求类型
//      con.setRequestProperty("Content-Length",Integer.toString(data.length()));  
        
        con.setDoOutput(true);  //默认是false,将 doOutput 标志设置为 true,指示应用程序要将数据写入 URL 连接。 
        con.setDoInput(true);   //默认是true,将 doInput 标志设置为 true,指示应用程序要从 URL 连接读取数据。
        con.setUseCaches(false);//如果为 true,则只要有条件就允许协议使用缓存。如果为 false,则该协议始终必须获得此对象的新副本。
        con.setInstanceFollowRedirects(true);

 //     con.connect();
        System.out.println("StreamTest...................");
  OutputStream o = con.getOutputStream();
  DataOutputStream d = new DataOutputStream(o);
  d.write("zy".getBytes());
//     d.flush();
 // d.close();
 // con.disconnect();
 
  
  BufferedReader bf = new BufferedReader(new InputStreamReader(con.getInputStream()));
  
  StringBuffer sf = new StringBuffer();
  String str;
  
  while((str=bf.readLine())!=null)
  {
   
   sf.append(str);
  }
  bf.close();

  d.close();  // ①   这里必须放在con.getInputStream()这句之后,否则会报socket错

 
  con.disconnect();
  
  
  System.out.println("StreamTestStr="+sf.toString());
  
  
  return null;

}

 

}

 

 

 

服务器端  StreamTestServer.java

 

public class StreamTestServer implements Controller{

 public ModelAndView handleRequest(HttpServletRequest req,
   HttpServletResponse res) throws Exception {
   
        BufferedReader bf = new BufferedReader(req.getReader());
  
  StringBuffer sf = new StringBuffer();
  String str;
  
  while((str=bf.readLine())!=null)
  {
   sf.append(str);
  }
  bf.close();
 
  System.out.println("StreamTestServer="+sf.toString());  
  
  if(sf.toString().equals("zy")){
   res.getWriter().write("123456");    // (1)
  }
 
  
  
  return null;
 }

}

 

输出结果为

StreamTest...................
StreamTestServer=zy
StreamTestStr=123456

 

Server端的(1)也可以改成 return new ModelAndView("test.jsp");

jsp中是要输出的内容,不过因为客户端读到的是源文件,所以要把jsp中无用的东西去掉,只写需要传回的信息

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值