Reputation: 5451
I have implemented a multithreaded client/server program in Java for downloading files, in which the server can concurrently serve the file to many clients by utilizing threads.
When I test the server with a single client it works fine, but when I test with ten or more clients using a shell script then the downloaded files all have different sizes, which differs from the actual size of the file on the server side.
Can anyone explain why this is happening?
Code for Server:
public class FileSend implements Runnable {
Socket sock;
String pathname;
FileSend(Socket s, String filename) {
sock = s;
pathname = System.getenv("HOME") + "/" + Main.spath + "/" + filename;
}
void send(String pathname) throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, ParseException {
try {
byte[] buf = new byte[1024];
OutputStream os = sock.getOutputStream();
//PrintWriter writer = new PrintWriter(os);
BufferedOutputStream out = new BufferedOutputStream(os, 1024);
int i = 0;
File fp = new File(pathname);
RandomAccessFile ra = new RandomAccessFile(fp, "r");
long bytecount = 1024;
////////////////
while ((i = ra.read(buf, 0, 1024)) != -1) {
bytecount += 1024;
out.write(buf, 0, i);
out.flush();
}
sock.shutdownOutput();
out.close();
ra.close();
sock.close();
} catch (IOException ex) {
}
}
public void run() {
try {
try {
try {
try {
send(this.pathname);
} catch (ParseException ex) {
Logger.getLogger(FileSend.class.getName()).log(Level.SEVERE,
null, ex);
}
} catch (NoSuchPaddingException ex) {
Logger.getLogger(FileSend.class.getName()).log(Level.SEVERE,
null, ex);
}
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(FileSend.class.getName()).log(Level.SEVERE, null,
ex);
}
} catch (IOException ex) {
Logger.getLogger(FileSend.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Client Code:
public class FileRecieve implements Runnable {
Socket sock;
String path;
Date T;
//private Date d2;
FileRecieve(Socket s, String fname, Date d1) {
sock = s;
path = Main.Dpath + "/" + fname;
T = d1;
}
public void run() {
try {
byte[] b = new byte[1024];
int len = 0;
long bytcount = 1024;
File fp = new File(path);
// RandomAccessFile ra = new RandomAccessFile(fp,"r");
RandomAccessFile ra = new RandomAccessFile(fp, "rw");
ra.seek(0);
InputStream is = sock.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while ((len = is.read(b, 0, 1024)) != -1) {
bytcount = bytcount + 1024;
//decrypt
ra.write(b, 0, len);
}
is.close();
ra.close();
sock.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Please help, many thanks in advance.
Upvotes: 0
Views: 159
Reputation: 612
I have made a similar attempt at a Mutithreaded Client-Server file downloader app. You can check it out at code review. I have used the java.util.concurrent package classes for the multithreading bit.
Upvotes: 1