【发布时间】:2017-11-10 08:51:50
【问题描述】:
我正在尝试通过 Java 套接字将文件从一个程序发送到另一个程序。我的代码基于this question。 问题是在托管服务器的 Ubuntu 机器上,发送过来的文件大小为 0 字节。该代码已在我的 Windows 笔记本电脑上的本地连接上运行,所以可能 问题出在与远程连接有关吗?
服务器代码:
int g = Integer.parseInt(in.readLine());
if(g > -1) {
InputStream fIn = client.getInputStream();
for(int i = 0; i < g; i++) {
String name = in.readLine();
byte[] bytes = new byte[16*1024];
File f = new File("plugins/" + name + ".jar");
if(!f.exists()) f.createNewFile();
FileOutputStream fOut = new FileOutputStream(f);
int count;
while ((count = fIn.read(bytes)) >= 0) {
fOut.write(bytes, 0, count);
}
fOut.flush();
fOut.close();
}
System.out.println("[" + client.getRemoteSocketAddress().toString() + "] added " + g + " new plugins.");
client.close();
}else{
client.close();
}
客户端代码:
JFileChooser fd = new JFileChooser("C:\\");
fd.setFileSelectionMode(JFileChooser.FILES_ONLY);
fd.setMultiSelectionEnabled(true);
fd.setFileFilter(new FileNameExtensionFilter(null,"jar"));
int r = fd.showOpenDialog(null);
if(r == JFileChooser.APPROVE_OPTION) {
File[] files = fd.getSelectedFiles();
OutputStream fOut = sock.getOutputStream();
out.println(files.length);
for(File f : files) {
out.println(f.getName().split("\\.")[0]);
byte[] bytes = new byte[16 * 1024];
FileInputStream fIn = new FileInputStream(f);
int count;
while ((count = fIn.read(bytes)) >= 0) {
fOut.write(bytes, 0, count);
}
fIn.close();
}
}else{
out.println(-1);
}
sock.close();
【问题讨论】:
-
client是什么对象?第一个元素/行是文件数。添加读取文件数量的部分?您的代码中存在不同的问题:流中没有分隔符告诉服务器文件的所有字节都已读取并且新文件开始。您的异常/资源处理。如果发生异常,您可能不会关闭所有流,这可能会成为服务器端真正的大问题。 -
@andih 客户端是一个套接字。对于连接到服务器的每个新客户端,套接字都会传递给一个线程,因此“服务器”代码嵌套在 run() 中。是的,第一行读取文件的数量,请参阅编辑。
-
@andih 也许您可以发布添加分隔符的答案?此外,我处理给定代码之外的异常。我的异常处理怎么会成为服务器端的“真正的大问题”?完成协议后,双方终止连接。如果在关闭客户端套接字时抛出服务器端错误,则线程结束。基本上,如果似乎有问题,那么双方都会终止。
-
exists()/createNewFile()部分完全是浪费时间和空间。new FileOutputStream()然后必须删除该文件并创建一个新文件。不要编写无意义的代码。三个系统调用都可以做。 -
@EJP 我不明白为什么这是完全重复的。通过套接字发送多个文件是问题的一方面。网上有不同的教程/示例如何通过套接字发送多个文件。 “主要”问题是为什么服务器端的文件大小为 0 字节。
标签: java sockets ubuntu server fileoutputstream