网服务器端发送消息并接受返回的消息(输出输入流应用)

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



客户端 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();
  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中无用的东西去掉,只写需要传回的信息

你可能感兴趣的:(jsp,应用服务器)