I am sending file from server to client using java socket programming. Here is my server side code:
public void fileSendingProtocol(String filePath) {
File myFile = new File(filePath);
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
System.err.println(ex);
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
os.write(mybytearray, 0, mybytearray.length);
os.flush();
System.out.println(filePath + " Submitted");
// File sent, exit the main method
} catch (IOException ex) {
// Do exception handling
System.out.println(ex.toString());
} finally {
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here i have closed the os in the finally block. Because if i omit os.close()
then i am not able to receive the file in the client side.
Here is my client file receiving code:
public static void fileReceivingProtocol(String filePath) {
try {
fos = new FileOutputStream(filePath);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
bos = new BufferedOutputStream(fos);
/* read question paper from the server. */
try {
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
fos.close();
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
I need the server first send a file . Then after receiving that file the client need to send another file to server after some minutes. But if i call the os.close() in the server side then my socket get closed and i am not able to continue any further communication between then.