• 欢迎浏览“String me = Creater\忠实的资深Linux玩家;”,请文明浏览,理性发言,有侵犯你的权益请邮件我(creater@vip.qq.com).
  • 把任何的失败都当作一次尝试,不要自卑;把所有的成功都想成是一种幸运,不要自傲。
  •    2年前 (2016-06-28)  java |   抢沙发  29 
    文章评分 1 次,平均分 5.0
    	class ReceiveThread extends Thread {
    		private InputStream mInputStream;
    		@Override  
    		public void run() {  
    			super.run();  
    			mInputStream = serialPort.getInputStream();
    			int maxLength = 2048;  //2016-06-26
    			byte[] buffer = new byte[maxLength];  
    			int available = 0;  
    			int currentLength = 0;   
    			int factPackLen = 6;  
    
    			while (!serialPort.isOpen) {
    				try {
    					Thread.sleep(2000);
    				} catch (InterruptedException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    			}
    			//while (!isInterrupted()) {  
    			while (true) {  
    				try {  
    					available = mInputStream.available();  
    					if (available > 0) {  
    						// 防止超出数组最大长度导致溢出  
    						//System.out.println("available+++++++++++++++++++++++++:"+available);  
    						if (available > maxLength - currentLength) {  
    							available = maxLength - currentLength;  
    						}  
    						mInputStream.read(buffer, currentLength, available);  
    						currentLength += available;  
    					}else{
    						Thread.sleep(10);
    					}
    				}  
    				catch (Exception e) {  
    					e.printStackTrace();  
    				}  
    				int cursor = 0;  
    				while (currentLength >= factPackLen) {  
    					if (buffer[cursor] != (byte)0xFB) {  
    						//System.out.println("未发现头部");
    						--currentLength;  
    						++cursor;  
    						continue;  
    					}  
    					if (currentLength < factPackLen) {  
    						break;  
    					} 
    					if(buffer[cursor + factPackLen - 1] != (byte)0xFE){
    
    						--currentLength;  
    						++cursor; 
    						continue;
    					}
    					// System.out.println("发现完整帧");
    					onDataReceived(buffer, cursor, factPackLen);  
    					currentLength -= factPackLen;  
    					cursor += factPackLen;   
    				}  
    				if (currentLength > 0 && cursor > 0) {  
    					System.arraycopy(buffer, cursor, buffer, 0, currentLength);  
    				}  
    			}  
    		}  
    	}  
    	protected void onDataReceived(final byte[] buffer, final int index, final int packlen) {  
    		byte[] buf = new byte[packlen];  
    		System.arraycopy(buffer, index, buf, 0, packlen);  
    		getUploadData(buf);
    	} 
     

    除特别注明外,本站所有文章均为String me = "Creater\忠实的资深Linux玩家";原创,转载请注明出处来自http://unix8.net/home.php/4932.html

    关于

    发表评论

    暂无评论

    切换注册

    登录

    忘记密码 ?

    切换登录

    注册

    扫一扫二维码分享