I am having a problems trying to send a file from a server program to a client program over a socket. SO fair I have tried splitting it into bytes but I haven’t had any success so far. Also the server must be concurrent so I am unsure where I should put the code to send the file.
Thanks
EDIT:
Here is the code that I have tried so far, at the moment It transfers a copy of the file into where its meant to be but the file size is zero bytes 🙁
In the Protocol class :
try {
File program = new File("./src/V2AssignmentCS/myProgram.jar");
byte[] mybytearray = new byte[4096];
FileInputStream fis = new FileInputStream(program);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray, 0, mybytearray.length);
os.flush();
} catch (IOException e) {
System.err.println("Input Output Error: " + e);
}
And on the client side :
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
// receive file
byte [] mybytearray = new byte [ServerResponse.programSize()];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("./src/V2AssignmentCS/newProgram.jar");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
// thanks to A. Cádiz for the bug fix
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
sock.close();
You are ignoring the result code returned by this method. Check the Javadoc. It isn’t what you clearly expect it to be.
Here you are writing exactly 4096 bytes. Was that your intention?
The canonical way to copy streams in Java, which you should be using at both ends, is as follows: