【发布时间】:2017-10-18 22:36:23
【问题描述】:
我使用波纹管代码将文件文件主文件发送到客户端,但是当我使用多个时间时,此代码用于不同的文件程序会给出“SOCKET CLOSED”错误,因为我使用“out.close();”和“in”关闭了套接字。关();”我无法解决这些问题你有什么建议吗?我也尝试不关闭套接字,但它不起作用下一个文件这次不发送
private void SendFiletoClient(Socket Socket, String fileName) {
try {
File file = new File(MasterPath + "/" + fileName);// Get the size of the file
long length = file.length();
byte[] bytes = new byte[16 * 1024];
InputStream in = new FileInputStream(file);
OutputStream out = Socket.getOutputStream();
int count;
while ((count = in.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/////
private void addFileToClient(Socket Socket, String fileName) {
File file = new File(MasterPath + fileName);
try {
file.createNewFile();
InputStream in = Socket.getInputStream();
OutputStream out = new FileOutputStream(MasterPath + fileName);
byte[] bytes = new byte[16 * 1024];
int count;
while ((count = in.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
【问题讨论】:
-
不要关闭套接字?
-
试了很多次都没用
-
file.createNewFile();在这里毫无意义。您正在强制文件系统 (a) 删除任何现有文件,(b) 创建一个新文件,然后 (c) 在执行new FileOutputStream()时再次执行所有这些操作。这完全是浪费时间和空间。