Android : Java Socket Sending Multiple Files but Received a Single File?

on Tuesday, September 9, 2014


Now this is very strange.... I have two android devices in which both of them operating one as a Server and another as a Client.


The problem is, When a Client send a file through socket. Server will receive it fine. But when Client try to send multiple files, then Server will only receive single file... why is like that?


I already did flushing the socket for each file from the list (client). But .... Why did the Server (receiver) code, only write a single file as its output?


Please cmiiw.


Here is the code for Server (receiving):



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;
while ((count = inp.read(bp, 0, bp.length)) != -1) {
bos.write(bp, 0, count);
}

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

}

}


and here is the code for Client (sending):



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

out.flush();
bis.close();
fis.close();

}

0 comments:

Post a Comment