【发布时间】:2014-09-10 06:47:14
【问题描述】:
现在这很奇怪.... 我有两个 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();
}
【问题讨论】:
-
请告诉服务器应该如何知道更多文件即将到来。服务器和客户端之间有什么协议?客户端发送什么?请先解释一下。解释代码。
-
在协议方面,请考虑code.google.com/p/protobuf
-
我认为在服务器端,我应该把......这个算法:“当它达到字节的最终长度时。它应该打破读取内容的循环。并启动一个新的 FileIO操作”我说的对吗? @greenapps
标签: java android file sockets file-transfer