socket InputStream读取数据的问题记录

在用java写socket client的发现一个问题,如果直接运行程序会报无法序列化的错误,但如果debug则不会报错,应该大半天的研究才发现问题在于java中从socket读取inputStream时,未必能一次性全部读取到,这可能应为网络延迟,也可能应为缓冲区还没有准备好,之前代码是这样:

public String readLine(int length) throws IOException {
		String buf = "";
		int index = 0;
		InputStream input = socket.getInputStream();
		
		while (true) {
			index = buf.indexOf("\r\n");
			if (index >= 0) {
				break;
			}
			
			byte[] data = new byte[length];
			input.read(data,length);
			String line = new String(data, Protocol.ENCODE);
			System.out.println("read line: " + off);
			buf += line;
			off += off;

		}
		return buf.substring(0, index);
	}

 应该修改为:

	public String readLine(int length) throws IOException {
		String buf = "";
		InputStream input = socket.getInputStream();
		int index = 0;
		while (true) {
			index = buf.indexOf("\r\n");
			if (index >= 0) {
				break;
			}
			int length0 = Math.min(input.available(), length);
			if (length0 == 0) {
				continue; //try again
			}
			byte[] data = new byte[length0];
			input.read(data);
			String line = new String(data, Protocol.ENCODE);
//			System.out.println(length0+","+line);
			buf += line;
		}
		return buf.substring(0, index);
	}

猜你喜欢

转载自san-yun.iteye.com/blog/1828872