Java套接字发送多个文件但收到单个文件?

时间:2014-09-09 09:07:19

标签: java android file sockets file-transfer

现在这很奇怪.... 我有两个Android设备,其中两个都在运行 一个用作服务器,另一个用作客户端。

问题是,当客户端通过套接字发送文件时。 服务器将收到它。但是当客户端尝试发送多个文件时 然后服务器只会收到单个文件...为什么会这样?

我已经从列表(客户端)为每个文件刷新了套接字。 但....为什么服务器(接收器)代码只写一个文件作为其输出?

请cmiiw。

以下是服务器(接收)的代码:

Socket bSock = serverSocket.accept();

    DataInputStream inp = new DataInputStream(
    bSock.getInputStream());

// reading the code first

int iCode = inp.readInt();

if(iCode == Request.STATE_FILESHARING){

                        // reading how many files will be found
    int manyFile = inp.readInt();
    String dName = null;

    for (int index = 0; index < manyFile; index++) {

    // reading the file name
    dName = inp.readUTF();

    // reading the file size
    byte bp[] = new byte[inp.readInt()];

    FileOutputStream fos = new FileOutputStream(SDTool.getCurrentLocalTransferPath() + "/" + dName);
    BufferedOutputStream bos = new BufferedOutputStream(fos);

    // reading the content
    int count;
    int fsize = 0;
    while ((count = inp.read(bp, 0, bp.length)) != -1) {
            fsize += count;
            bos.write(bp, 0, count);

             // this will exist the loop of reading
            if(fsize == bp.length)
            break;

        }

    bos.close();
    fos.close();

    }

}

以下是客户端(发送)的代码:

socket = new Socket(myServerAddress, SocketServerPORT);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());

double dTotalSize = getTotalSize(nList);
int iTotalTransferred = 0;
double dPercentage = 0;

DecimalFormat df = new DecimalFormat("#.00");

// sending multiple files state
out.writeInt(Request.STATE_FILESHARING);
// sending how many files required to be accepted
out.writeInt(nList.size());

for (Item o : nList) {
        File myFile = new File(o.getPath());
        byte[] mybytearray = new byte[(int) myFile.length()];
        FileInputStream fis = new FileInputStream(myFile);
        BufferedInputStream bis = new BufferedInputStream(fis);
        // bis.read(mybytearray, 0, mybytearray.length);

        // set the code, the file name, and then the size
        out.writeUTF(myFile.getName()); 
        out.writeInt(mybytearray.length);


            int len = 0;        int fsize = 0;
            // here is the content      
            while ((len = bis.read(mybytearray)) != -1) {
                    fsize += len;
                    dPercentage = (double) ((fsize * 100) / dTotalSize);
                    dPercentage = Math.round(dPercentage);
                    out.write(mybytearray, 0, len);
                    updateProgressUploadUI(dPercentage); 
            if(fsize == mybytearray.length){
            out.flush();                       
            }
        }


        bis.close(); 
        fis.close();

}

1 个答案:

答案 0 :(得分:1)

您正在读取第一个文件,直到流结束,这仅在发件人在发送完最后一个文件后关闭套接字时才会发生。因此,您将所有文件视为单个流。您需要将读取循环限制为仅读取每个文件中的确切字节数。我已在此处多次发布必要的代码,例如here

相关问题