【发布时间】:2015-07-24 03:01:44
【问题描述】:
我在通过套接字 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;
}
【问题讨论】: