gpt4 book ai didi

Java Socket 发送多个文件但收到单个文件?

转载 作者:行者123 更新时间:2023-12-01 12:33:42 25 4
gpt4 key购买 nike

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

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

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

请注意。

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

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();

}

最佳答案

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

关于Java Socket 发送多个文件但收到单个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25740672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com