我在通过套接字java发送文件时遇到问题。有时代码工作,有时不工作。我在两者中测试while块,似乎代码发送所有字节,但服务器没有接收(但即使在此测试中,文件也正确发送)。在这种情况下,服务器停止接收数据。所有文件大约150Kb。我正在使用9191端口。
服务器:
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();
}
}
客户:
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;
}
答案 0 :(得分:1)
首先,您应该分别用ObjectInputStream
和ObjectOutputStream
替换DataInputStream
和DataOutputStream
。您没有序列化java对象,使用专门用于此目的的流类是没有意义的。
其次,您在客户端发送文件长度,但没有在服务器中专门读取它。而是将其添加到文件的开头。
答案 1 :(得分:1)
在客户端上,你说,
out.writeUTF(file.getName());
out.writeLong(file.length());
但是在你说的服务器上,
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();
您没有读取文件长度。并且您需要确保读取所有发送的字节(或者您的文件将被损坏)。另外,请勿忘记close()
FileOutputStream
(或使用try-with-resources
为您关闭它)。像,
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);
}
}