socket InputStream读取数据的问题记录

  • Post author:
  • Post category:其他


在用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原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。