gpt4 book ai didi

java - 使用套接字传输大文件

转载 作者:搜寻专家 更新时间:2023-10-31 08:05:16 25 4
gpt4 key购买 nike

当我使用套接字编程传输大文件时,收到的文件不完整,即它是一个 mp3 文件,当我播放时听起来很奇怪。代码是:

服务器端:

File myFile = new File("abc.mp3");
{
Socket sock = servsock.accept();
int packetsize=1024;
double nosofpackets=Math.ceil(((int) myFile.length())/packetsize);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
for(double i=0;i<nosofpackets+1;i++) {
byte[] mybytearray = new byte[packetsize];
bis.read(mybytearray, 0, mybytearray.length);
System.out.println("Packet:"+(i+1));
OutputStream os = sock.getOutputStream();
os.write(mybytearray, 0,mybytearray.length);
os.flush();
}
}

客户端:

int packetsize=1024;
FileOutputStream fos = new FileOutputStream("zz.mp3");
BufferedOutputStream bos = new BufferedOutputStream(fos);
double nosofpackets=Math.ceil(((int) (new File("abc.mp3")).length())/packetsize);
for(double i=0;i<nosofpackets+1;i++)
{
InputStream is = sock.getInputStream();
byte[] mybytearray = new byte[packetsize];
int bytesRead = is.read(mybytearray, 0,mybytearray.length );
System.out.println("Packet:"+(i+1));
bos.write(mybytearray, 0,mybytearray.length);
}
sock.close();
bos.close();

在客户端,为了简单起见,我使用了 new File("abc.mp3")).length(我可以从服务器端发送文件的长度)。

如果客户端和服务器在同一台机器上,这段代码可以完美运行,但如果它们在不同的机器上,文件就会失真。

最佳答案

在 Java 中复制流的规范方式:

int count;
byte[] buffer = new byte[8192];
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}

适用于任何大于零的缓冲区大小。应极力避免将缓冲区大小与输入大小相关联的诱惑。

关于java - 使用套接字传输大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5113914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com