Reputation: 1
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;
}
Upvotes: 0
Views: 605
Reputation: 201409
On the client you say,
out.writeUTF(file.getName());
out.writeLong(file.length());
But on the server you say,
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();
You didn't read the file length. And you need to make sure you read all of the sent bytes (or your file will be corrupt). Also, don't forget to close()
the FileOutputStream
(or use a try-with-resources
to close it for you). Something like,
String fileName = in.readUTF();
try (FileOutputStream fos = new FileOutputStream(destinationPath
+ fileName)) {
long size = in.readLong();
byte[] buf = new byte[1024];
long total = 0;
int len;
while ((len = in.read(buf)) >= 0) {
fos.write(buf, 0, len);
total += len;
}
if (total != size) {
System.err.printf("Expected %d bytes, but received %d bytes%n",
size, total);
}
}
Upvotes: 1
Reputation: 2088
First you should replace ObjectInputStream
and ObjectOutputStream
with DataInputStream
and DataOutputStream
respectively. You are not serializing java objects and it makes no sense to use stream classes meant for that purpose.
Second you are sending the file length in the client but not specifically reading it in the server. It is instead getting added to the beginning of the file.
Upvotes: 1