Socket使用中读取响应消息的3种方法

类1:一次性全部读取。

代码:
方法一:
public String getResultStr(Socket sourceSocket)
{

String resultStr = null;

InputStream in;
try {
in = sourceSocket.getInputStream();
int readIndex = 5 * 1024 * 1024;
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(in), readIndex);
char[] charArray = new char[readIndex];
int read_rst = bufferedReader.read(charArray);
resultStr = new String(charArray, 0, read_rst);
bufferedReader.close();

} catch (IOException e) {
e.printStackTrace();
}

return resultStr;
}

类2:非一次性读取

方法二:一行行读
public String getResultStr(Socket sourceSocket)
{
String resultStr = null;

InputStream in;

try {
in = sourceSocket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(in));
StringBuffer responseBuffer = new StringBuffer();
String line = bufferedReader.readLine();
while (null != line)
{
responseBuffer.append(line);
line = bufferedReader.readLine();
}

bufferedReader.close();

resultStr = responseBuffer.toString();

} catch (IOException e) {
e.printStackTrace();
}

return resultStr;
}


方法三:一字节一字节读
public String getResultStr(Socket sourceSocket)
{
String resultStr = null;

InputStream in = null;

try {
in = sourceSocket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(in));

int read_rst = bufferedReader.read();

StringBuffer readBuffer = new StringBuffer();
while (-1 != read_rst)
{
char singleChar = (char) read_rst;

readBuffer.append(singleChar);
}

bufferedReader.close();

resultStr = readBuffer.toString();
} catch (IOException e) {
e.printStackTrace();
}

return resultStr;
}


其中方法一的优点是读取速度快,且不用被超时所扰。缺陷是,只能读取一定量的字节,虽然BufferedReader的构造方法提供了设置缓冲区大小的功能,但是不管设多大,都只能读取一定量的字节,据项目中的情况来看,是65536个。如果响应消息有几MB的话,这种方法是肯定不行的。但是如果读取的消息很小,在65536个字节以内,则可以使用。

方法二的优点是便于做读取后的算法操作,速度嘛也挺快。缺陷是不能精确读取。因为readLine的方法读不出’\n’,’\r\n’,所以读出来的内容其长度与实际长度有出入。

方法三是最优解。(以上只是三种方法的原型,具体业务还要具体实现)


java download



	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		/*

		String testURL = "http://www.douban.com/subject/2132932/";
		HttpURLConnection conn = (HttpURLConnection) new URL(testURL)
				.openConnection();
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.connect();
		conn.getOutputStream().write("".getBytes());
		BufferedReader reader = new BufferedReader(new InputStreamReader(conn
				.getInputStream(), "GBK"));

		
		String line = null;
		while ((line = reader.readLine()) != null) {
			// out.write(line);

		}*/
		Writer out = resp.getWriter();
		out.write("begin");
		String path = req.getParameter("path");
		out.write(path);
		download(path, resp);

	}
	
	public HttpServletResponse download(String path, HttpServletResponse response) throws MalformedURLException{
		
		 URL url = new URL(path);
       try {
           // path是指欲下载的文件的路径。
           File file = new File(path);
           // 取得文件名。
           String filename = file.getName();
           // 取得文件的后缀名。
           String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

           // 以流的形式下载文件。
          // InputStream fis = new BufferedInputStream(new FileInputStream(path));
           
           URLConnection conn = url.openConnection();
           InputStream fis = conn.getInputStream();
           
           
           byte[] buffer = new byte[fis.available()];
           fis.read(buffer);
           fis.close();
           // 清空response
           response.reset();
           // 设置response的Header
           response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
           response.addHeader("Content-Length", "" + file.length());
           OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
           response.setContentType("application/octet-stream");
           toClient.write(buffer);
           toClient.flush();
           toClient.close();
       } catch (IOException ex) {
           ex.printStackTrace();
       }
       return response;
   }
	

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}





你可能感兴趣的:(算法,socket,ext)