java 网络读取,多次read,demo _JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java 网络读取,多次read,demo

java 网络读取,多次read,demo

 2011/9/29 8:03:02  chenliang1234576  http://chenliang1234576.iteye.com  我要评论(0)
  • 摘要:publicbyte[]doConnNetWork(byte[]outputBytes)throwsIOException{byte[]result=null;Socketconnection=null;OutputStreamoutputStream=null;InputStreaminputStream=null;intc=0;booleanisGo=true;//是否继续//只讲重点的,其他的忽略掉了connection=openConnection();inputStream=this
  • 标签:
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;
	} 

?

  • 相关文章
发表评论
用户名: 匿名