I have a problem sending files through socket java. Sometimes the code works, sometimes not. I test the while block in both, it seems the code is sending all the bytes, but the server is not receiving (but even in this test, the file is sent correctly). In this case, the server stopped receive data. All files are about 150Kb. I'm using the port 9191.
Server:
while (true) {
try {
Socket socket = ss.accept();
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
String fileName = in.readUTF();
FileOutputStream fos = new FileOutputStream(destinationPath + fileName);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) >= 0) {
fos.write(buf, 0, len);
}
fos.flush();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Client:
try {
Socket socket = new Socket(host, port);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
out.writeUTF(file.getName());
out.writeLong(file.length());
FileInputStream in = new FileInputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) >= 0) {
out.write(buf, 0, len);
}
out.close();
socket.close();
} catch (Exception e) {
throw e;
}