【发布时间】:2019-07-17 17:56:00
【问题描述】:
我想通过套接字连接发送多个文件。对于一个文件,它可以完美运行,但如果我尝试发送多个(一次一个),我会收到Socket Exception:
java.net.SocketException: 套接字关闭
一般来说,我的连接是这样工作的:
- 服务器等待连接
- 客户端连接到服务器并发送对某个文件的请求(包含文件名的字符串)
- 服务器读取本地文件并发送给客户端
- 客户端发送另一个文件的另一个请求并在第 3 点继续。
waiting-for-request 过程的运行方法如下所示:
@Override
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
if (message.equals(REQUESTKEY)) {
System.out.println("read files from directory and send back");
sendStringToClient(createCodedDirContent(getFilesInDir(new File(DIR))), socket);
} else if (message.startsWith(FILE_PREFIX)) {
String filename = message.substring(FILE_PREFIX.length());
try {
sendFile(new File(DIR + filename));
} catch (IOException e) {
System.err.println("Error: Could not send File");
e.printStackTrace();
}
} else {
System.out.println("Key unknown!");
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
而我的sendFile() 方法看起来像这样:
public void sendFile(File file) throws IOException {
FileInputStream input = new FileInputStream(file);
OutputStream socketOut = socket.getOutputStream();
System.out.println(file.getAbsolutePath());
int read = 0;
while ((read = input.read()) != -1) {
socketOut.write(read);
}
socketOut.flush();
System.out.println("File successfully sent!");
input.close();
socketOut.close();
}
我认为问题在于socketOut.close()。不幸的是,该方法也关闭了套接字连接(进一步连接的问题)。但是,如果我忽略此关闭,则文件传输将无法正常工作:文件到达客户端时不完整。
如何避免或解决此问题?或者有没有更好的方法来传输多个请求的文件?
谢谢
【问题讨论】:
-
您需要告诉您的客户文件有多大。否则,您只是在流式传输字节,没有尽头。客户不知道何时停止阅读。想想两者之间的通信(协议)。
标签: java sockets file-transfer