1. 程式人生 > >socket通訊 tcp/ip協議的拆包解包

socket通訊 tcp/ip協議的拆包解包

byte []surplusPack;
private void getCount() {
    // 監聽訊息
new Thread(new Runnable() {
        @Override
public void run() {
            while (true) {
                try {
//socket通訊的輸入流
                    if (inputStream != null) {
                        int lenth = -1;
                        byte[] buf = new byte
[1024 * 10]; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); while ((lenth = inputStream.read(buf)) != -1) { byteArrayOutputStream.write(buf, 0, lenth); byte[] packages = byteArrayOutputStream.toByteArray(); //將接受到的資料包裝成ByteBuffer
if (surplusPack==null){ //Log.d("vsvsvs12",new String(packages)); jixishuju(packages); }else {
                                byte[] allPacksge=new byte[surplusPack.length+packages.length];
                                System.arraycopy(surplusPack
,0,allPacksge,0,surplusPack.length); System.arraycopy(packages,0,allPacksge,surplusPack.length,packages.
ength);
                                //Log.d("vsvsvs11",new String(packages));
jixishuju(allPacksge);
                            }
                            byteArrayOutputStream.reset();
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();

}
public static int len=0;
private  synchronized void jiexishuju(byte[] allPacksge) {
    ByteBuffer bufpackages = ByteBuffer.wrap(allPacksge);
    //對比前4個位元組轉成的整數大小和整個資料包的大小
if (allPacksge.length>=4){
        byte[] packagecount=new byte[4];
        bufpackages.get(packagecount);
        len=ByteConverter.byteToInt2(packagecount);
        //Log.d("vsvsvs14",new String(allPacksge));
if (allPacksge.length>=len){
           // Log.d("vsvsvs","333333");
byte[] packagecontent=new byte[len];
            //給陣列賦值
ByteBuffer.wrap(allPacksge).get(packagecontent);
            //獲取單個數據包的大小
ByteBuffer onePackage = (ByteBuffer) ByteBuffer.wrap(packagecontent).position(7);
            //清楚已經獲取的
surplusPack=new byte[allPacksge.length-packagecontent.length];
            System.arraycopy(allPacksge,packagecontent.length,surplusPack,0,surplusPack.length);
            CharBuffer charBuffer;
            try {
                charBuffer = Charset.forName("UTF-8").newDecoder().decode(onePackage);
                final String info = charBuffer.toString();
                runOnUiThread(new Runnable() {
                    @Override
public void run() {
                        parseinfo(info);
                    }
                });
                jiexishuju(surplusPack);
                Log.d("vsvsvs11",new String(surplusPack));
                //getSurplusPackCount(surplusPack);
} catch (IOException e) {
                e.printStackTrace();
                e.printStackTrace();
            }
        }else{
            surplusPack=allPacksge;
        }
    }else {
        surplusPack=allPacksge;
    }
}