OkSocket接收所有數據,可以不固定協議頭;

這個是OkSocket的源碼地址:https://github.com/xuuhaoo/OkSocket

這個框架必須要固定包頭,我們在實際的使用中一般都是固定包頭的,但是爲了方便調試或者沒有固定包頭的,我們需要修改一下源碼;

把源碼中的這個接收消息類'ReaderImpl'修改一下:

public class ReaderImpl extends AbsReader {

//    private ByteBuffer mRemainingBuf;
//
//    @Override
//    public void read() throws RuntimeException {
//        OriginalData originalData = new OriginalData();
//        IReaderProtocol headerProtocol = mOkOptions.getReaderProtocol();
//        int headerLength = headerProtocol.getHeaderLength();
//        ByteBuffer headBuf = ByteBuffer.allocate(headerLength);
//        headBuf.order(mOkOptions.getReadByteOrder());
//        try {
//            if (mRemainingBuf != null) {
//                mRemainingBuf.flip();
//                int length = Math.min(mRemainingBuf.remaining(), headerLength);
//                headBuf.put(mRemainingBuf.array(), 0, length);
//                if (length < headerLength) {
//                    //there are no data left
//                    mRemainingBuf = null;
//                    readHeaderFromChannel(headBuf, headerLength - length);
//                } else {
//                    mRemainingBuf.position(headerLength);
//                }
//            } else {
//                readHeaderFromChannel(headBuf, headBuf.capacity());
//            }
//            originalData.setHeadBytes(headBuf.array());
//            if (SLog.isDebug()) {
//                SLog.i("read head: " + BytesUtils.toHexStringForLog(headBuf.array()));
//            }
//            int bodyLength = headerProtocol.getBodyLength(originalData.getHeadBytes(), mOkOptions.getReadByteOrder());
//            if (SLog.isDebug()) {
//                SLog.i("need read body length: " + bodyLength);
//            }
//            if (bodyLength > 0) {
//                if (bodyLength > mOkOptions.getMaxReadDataMB() * 1024 * 1024) {
//                    throw new ReadException("Need to follow the transmission protocol.\r\n" +
//                            "Please check the client/server code.\r\n" +
//                            "According to the packet header data in the transport protocol, the package length is " + bodyLength + " Bytes.\r\n" +
//                            "You need check your <ReaderProtocol> definition");
//                }
//                ByteBuffer byteBuffer = ByteBuffer.allocate(bodyLength);
//                byteBuffer.order(mOkOptions.getReadByteOrder());
//                if (mRemainingBuf != null) {
//                    int bodyStartPosition = mRemainingBuf.position();
//                    int length = Math.min(mRemainingBuf.remaining(), bodyLength);
//                    byteBuffer.put(mRemainingBuf.array(), bodyStartPosition, length);
//                    mRemainingBuf.position(bodyStartPosition + length);
//                    if (length == bodyLength) {
//                        if (mRemainingBuf.remaining() > 0) {//there are data left
//                            ByteBuffer temp = ByteBuffer.allocate(mRemainingBuf.remaining());
//                            temp.order(mOkOptions.getReadByteOrder());
//                            temp.put(mRemainingBuf.array(), mRemainingBuf.position(), mRemainingBuf.remaining());
//                            mRemainingBuf = temp;
//                        } else {//there are no data left
//                            mRemainingBuf = null;
//                        }
//                        //cause this time data from remaining buffer not from channel.
//                        originalData.setBodyBytes(byteBuffer.array());
//                        mStateSender.sendBroadcast(IOAction.ACTION_READ_COMPLETE, originalData);
//                        return;
//                    } else {//there are no data left in buffer and some data pieces in channel
//                        mRemainingBuf = null;
//                    }
//                }
//                readBodyFromChannel(byteBuffer);
//                originalData.setBodyBytes(byteBuffer.array());
//            } else if (bodyLength == 0) {
//                originalData.setBodyBytes(new byte[0]);
//                if (mRemainingBuf != null) {
//                    //the body is empty so header remaining buf need set null
//                    if (mRemainingBuf.hasRemaining()) {
//                        ByteBuffer temp = ByteBuffer.allocate(mRemainingBuf.remaining());
//                        temp.order(mOkOptions.getReadByteOrder());
//                        temp.put(mRemainingBuf.array(), mRemainingBuf.position(), mRemainingBuf.remaining());
//                        mRemainingBuf = temp;
//                    } else {
//                        mRemainingBuf = null;
//                    }
//                }
//            } else if (bodyLength < 0) {
//                throw new ReadException(
//                        "read body is wrong,this socket input stream is end of file read " + bodyLength + " ,that mean this socket is disconnected by server");
//            }
//            mStateSender.sendBroadcast(IOAction.ACTION_READ_COMPLETE, originalData);
//        } catch (Exception e) {
//            ReadException readException = new ReadException(e);
//            throw readException;
//        }
//    }
//
//    private void readHeaderFromChannel(ByteBuffer headBuf, int readLength) throws IOException {
//        for (int i = 0; i < readLength; i++) {
//            byte[] bytes = new byte[1];
//            int value = mInputStream.read(bytes);
//            if (value == -1) {
//                throw new ReadException(
//                        "read head is wrong, this socket input stream is end of file read " + value + " ,that mean this socket is disconnected by server");
//            }
//            headBuf.put(bytes);
//        }
//    }
//
//
//    private void readBodyFromChannel(ByteBuffer byteBuffer) throws IOException {
//        while (byteBuffer.hasRemaining()) {
//            try {
//                byte[] bufArray = new byte[mOkOptions.getReadPackageBytes()];
//                int len = mInputStream.read(bufArray);
//                if (len == -1) {
//                    break;
//                }
//                int remaining = byteBuffer.remaining();
//                if (len > remaining) {
//                    byteBuffer.put(bufArray, 0, remaining);
//                    mRemainingBuf = ByteBuffer.allocate(len - remaining);
//                    mRemainingBuf.order(mOkOptions.getReadByteOrder());
//                    mRemainingBuf.put(bufArray, remaining, len - remaining);
//                } else {
//                    byteBuffer.put(bufArray, 0, len);
//                }
//            } catch (Exception e) {
//                throw e;
//            }
//        }
//        if (SLog.isDebug()) {
//            SLog.i("read total bytes: " + BytesUtils.toHexStringForLog(byteBuffer.array()));
//            SLog.i("read total length:" + (byteBuffer.capacity() - byteBuffer.remaining()));
//        }
//    }


    //接收byte數組
    @Override
    public void read() throws RuntimeException {
        OriginalData originalData = new OriginalData();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            while (true) {
                byte[] buff = new byte[1024 * 5];
                int len = mInputStream.read(buff);
                bos.write(buff, 0, len);
                originalData.setBodyBytes(bos.toByteArray());
                mStateSender.sendBroadcast(IOAction.ACTION_READ_COMPLETE, originalData);
                bos.reset();
            }
        } catch (Exception e) {
            ReadException readException = new ReadException(e);
            throw readException;
        }
    }

    //接收byte數組
//    @Override
//    public void read() throws RuntimeException {
//        OriginalData originalData = new OriginalData();
//        try {
//            while (true) {
//                byte[] buff = new byte[1024 * 5];
//                int len = mInputStream.read(buff);
//                byte[] data = Arrays.copyOfRange(buff, 0, len);
//                originalData.setBodyBytes(data);
//                mStateSender.sendBroadcast(IOAction.ACTION_READ_COMPLETE, originalData);
//            }
//        } catch (Exception e) {
//            ReadException readException = new ReadException(e);
//            throw readException;
//        }
//    }


    //接收String
//    @Override
//    public void read() throws RuntimeException {
//        OriginalData originalData = new OriginalData();
//        try {
//            String response = "";
//            while (true) {
//                byte[] b = new byte[1024];
//                int len = mInputStream.read(b);
//                response = new String(b, 0, len);
//                originalData.setBodyBytes(response.getBytes());
//                mStateSender.sendBroadcast(IOAction.ACTION_READ_COMPLETE, originalData);
//            }
//        }catch (IOException e){
//           e.printStackTrace();
//        }
//    }

}

代碼中有註釋,可以選擇接收String或Byte數組;需要把原有的read()方法註釋;現把數據全部都讀到了BobyBytes中,獲取數據就 originalData.getBodyBytes() 就行了;

附:本人是項目剛開始就使用的OkSocket作爲通訊框架,但後來實際調試中頻繁出錯,原因是包頭轉義後長度就不固定了,包體也是會轉義的,導致經常接收不到完整的消息;但是現有通訊的心跳、重連機制、消息接收以及各種回調都使用的OkSocket,才被迫修改源碼;

如果OkSocket框架規則(包頭定長 ,根據包頭信息確定包體的長度)不符合你現在的通訊協議,就比如包頭有可能被轉義 轉義後的包頭就是不固定長度的了。還是不要使用此框架的好,畢竟改了框架的源碼;可以看一下這個:Android Socket長連接的使用和封裝

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章