在我的项目中,我尝试向每个连接的客户端发送一个文件,我使用线程将文件发送到clients.But,当我尝试测试时,我发现总共7个客户端中有3个客户端获得了完整的pdf文件,但其余的客户端只获得了一些字节。在java套接字编程中实现文件传输的有效方法是什么,使我可以同时将一个文件发送到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();
}
发布于 2018-10-25 21:59:37
我建议做出以下改变:
您可以将FileOutputStream
设置为将接收到的字节附加到文件。这样,您就不必确保将它们写到正确的位置。
out = new FileOutputStream(x+"/Desktop/"+Helper.courseCode+".pdf", true);
因此,文件的写入可以像这样完成:
int count = 0;
while ((count = in.read(bytes)) > 0) {
System.out.println("v : " + count);
out.write(bytes, 0, count);
}
如果这不能解决您的问题,您应该向我们展示处理套接字的代码。
https://stackoverflow.com/questions/52989373
复制相似问题