【发布时间】:2018-10-26 06:13:56
【问题描述】:
在我的项目中,我正在尝试向每个连接的客户端发送文件。我使用线程向客户端发送文件。但是当我尝试对此进行测试时,我发现总共 7 个客户端中的 3 个客户端获得了完整的 pdf 文件,但是其余的只有一些字节。 java socket编程中实现文件传输的有效方法是什么,让我可以同时向100多个客户端发送文件?
文件发送代码
while(true){
try {
if(Helper.sendFile)
{
System.out.println("file sending...");
File file = new File(Helper.quesPath);
// 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);
System.out.println("ec : "+count);
}
//out.close();
out.flush();
in.close();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
文件接收代码
while (true)
{
if(Helper.sendFile)
{
try {
in = socket.getInputStream();
String x=System.getProperty("user.home");
out = new FileOutputStream(x+"/Desktop/"+Helper.courseCode+".pdf");
System.out.println(x);
byte[] bytes = new byte[16*1024];
int count;
while (true) {
count = in.read(bytes);
System.out.println("v : "+count);
if(count < 16380){
out.write(bytes, 0, count);
break;
}else{
out.write(bytes, 0, count);
}
}
System.out.println("File Done");
//in.close();
out.close();
break;
} catch (Exception ex) {
System.out.println("File not found. ");
}
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
【问题讨论】:
-
您无法使用 FTP 库吗?除非你需要一些特殊的轮子,否则避免重新发明轮子。
-
同意你不要重新发明轮子你可以使用 putty sftp
-
这是一个关于如何通过套接字传输数据的简单问题。 OP 没有理由不尝试让它工作并了解问题可能出在哪里。他并不是在重新发明轮子,只是在学习套接字编程的工作原理。
标签: java sockets file-transfer