[英]Java File transfer using socket programming
在我的项目中,我试图向每个连接的客户端发送文件。我使用线程向客户端发送文件。但是当我尝试测试时,我发现总共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();
}
我认为您在从客户端读取信息时遇到了问题。
我假设魔术数字16380是文件的预期长度。 因此,您需要做的是一些不同的事情:
int count = 0;
while (count < 16380) {
int incoming = in.read(bytes);
System.out.println("v : " + incoming);
if (incoming > 0) {
out.write(bytes, 0, incoming);
count += incoming;
} else if (incoming < 0) {
//end of stream
break;
}
}
该循环将继续循环,直到读取的字节数( count
)达到您的幻数为止。
我还将做的事情是使用更有效的输入流,例如BufferedInputStream
。
因此,在代码块的第一行中,您需要执行以下操作:
in = new BufferedInputStream(socket.getInputStream());
如果您需要大量的并发连接,则可以考虑使服务器不受NIO的阻塞。 但是范例有点不同。
我建议这些更改:
您可以将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);
}
如果这不能解决您的问题,则应向我们显示处理套接字的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.