回复的数据有几百K,客户端要支持拆包,拆包是怎样做的?

解决方案 »

  1.   

    如果你使用TCP协议(也就是直接使用Socket类),你发送的数据是会被底层自动拆包的,你连续发送都可以保证可以正常的发送到对方那里。
    你不能直接控制拆包的过程,即使你希望按你要求拆包,最多只能每write一定字节后调用flush方法使刷新本地的Cache,但是并不能保证底层没有再拆包的
      

  2.   

    就是说,我在客户端接收的时候只要用read方法读完字节流就好了,并不用写什么特别的拆包代码对不对?
      

  3.   

    socket层的API控制不了底层拆包吧?
      

  4.   

    谁说拆不了包.不懂就不要乱说给个方法给你看看  
    //这个方法是解包判断传输情况
      private void upPackage(byte[] data) {
            ByteArrayInputStream bias = new ByteArrayInputStream(data);
            DataInputStream biasDis = new DataInputStream(bias);
            int type = 0;
            try {
                type = biasDis.readInt();
            } catch (SocketTimeoutException ex) {
                setError("网络超时!");
            } catch (IOException ex1) {
                setError("对方取消了文件传输或网络错误!");
            }
            switch (type) {
            case PACKAGE_TYPE_FILENAME: {
                try {
                    int length = biasDis.readInt();
                    bias.read(dataBuf,0,length);
                    fileName = new String(dataBuf,0,length);
                    fileSize = biasDis.readLong();
                    length = biasDis.readInt();
                    if (length !=-1) {
                        bias.read(dataBuf,0,length);
                        message = new String(dataBuf,0,length);
                    }
                    fileTransStatus = FILE_TRANS_STATUS_WAITFORCONFIRM;
                } catch (SocketTimeoutException ex) {
                    setError("网络超时!");
                } catch (IOException ex) {
                    setError("对方取消了文件传输或网络错误!");
                }
                break ;
            }
            case PACKAGE_TYPE_CONTEXT: {
                try {
                    int flag = biasDis.readInt();
                    int length = biasDis.readInt();
                    bias.read(dataBuf,0,length);
                    writeToFile(dataBuf,0,length);
                    transFileLength += length;
                    if (flag == 0) {
                        fileTransStatus = FILE_TRANS_STATUS_SUCCESS;
                        stopThread();
                    }
                } catch (SocketTimeoutException ex) {
                    setError("网络超时!");
                } catch (IOException ex) {
                    setError("对方取消了文件传输或网络错误!");
                }
                break ;
            }
            }
        }