带套接字的大文件传输 [英] Large file transfer with sockets

查看:97
本文介绍了带套接字的大文件传输的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I'm transferring a large file using socket programming, the received file is incomplete i.e. it is an mp3 file which when i play sounds weird. The code is:

服务器端:

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();

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

On the Client side I have used new File("abc.mp3")).length just for simplicity (I could send the length of the file from the server side).

如果客户端,此代码可以正常工作和服务器是同一台机器,但如果它们在不同的机器上,文件就会失真。

This code works perfectly if client and server are the same machine, but the file gets distorted if they are on different machines.

推荐答案

复制a的规范方法Java中的流:

The canonical way to copy a stream in Java:

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

适用于任何大于零的缓冲区大小。应该尽量避免将缓冲区大小与输入大小联系起来的诱惑。

Works with any buffer size greater than zero. The temptation to relate the buffer size to the input size should be strenuously avoided.

这篇关于带套接字的大文件传输的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆