`
chenliang1234576
  • 浏览: 195071 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

java 网络读取,多次read,demo

    博客分类:
  • Java
阅读更多
public byte[] doConnNetWork(byte[] outputBytes) throws IOException {
		byte[] result = null; 
		Socket connection = null;
		OutputStream   outputStream = null;
		InputStream    inputStream = null; 
		int c = 0;
		boolean isGo = true; // 是否继续
		// 只讲重点的,其他的忽略掉了
		    connection =  openConnection(); 
		    inputStream = this.openConnectionInputStream(connection); 
		    outputStream = this.openConnectionOutputStream(connection); 
			 //***  从服务器端接受数据  ***//  
		while (c < 3 && isGo) { 
//--------------------------------------------- 读取数据核心代码 start ----------------------------------
			int hLen = 18;
			byte[] header = new byte[hLen];
			inputStream.read(header, 0, hLen);
			// 读取包头
			ResponseHeader rheader = DataPackage.getResponseHeader(header);
			int len = rheader.getDwDataLen();
			REQUEST_TYPE = rheader.getRequestType();
			// 解析header,得到数据长度len
			byte[] content = new byte[len];
			while (inputStream.available() < len) {
				try {
					Thread.sleep(10);
				//	System.out.println(" len --> " + len); 
				} catch (InterruptedException e) { 
					e.printStackTrace();
				}
			}
			  inputStream.read(content, 0, len);
			//int rLen =  
			//System.out.println(" len --> " + len + "  read Len ->" + rLen);
			if (len > 0) {
				result = new byte[hLen + len];
				System.arraycopy(header, 0, result, 0, hLen);
				System.arraycopy(content, 0, result, hLen, len);
			} else {
				result = header;
			}
//---------------------------------------------- 读取数据核心代码 end -------------------------------------- 
		 	 	 c++;
			} 
			closeConnection(connection, outputStream, inputStream);  
			 
		return result;
	} 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics