将文件从服务器传输到客户端的速度非常低

时间:2016-09-12 15:03:32

标签: java performance networking download

我正在使用套接字从服务器下载45 MB的文件。虽然测量我的系统流量显示我的下载速度大约为4 MB / s,但在Java中,我只测量60 KB / s。

客户端双面:

int fileSize = Network.in.readInt(); //DataInputStream
byte[] data = new byte[fileSize];
for(int i = 0;i < data.length;i++)
{
    if(i % 1024 == 0)Log.info("Downloading: " + (i / 1024) + " KB / " + (fileSize / 1024) + " KB");
    data[i] = Network.in.readByte();
}
//int bytesRead = Network.in.read(data,0,data.length);
//int current = bytesRead;
//
//do {if(current % 16384 == 0)Log.info("Downloading: " + (current / 1024) + " KB / " + (fileSize / 1024) + " KB");
//     bytesRead = Network.in.read(data, current, (data.length-current));
//     if(bytesRead >= 0) current += bytesRead;
//} while(bytesRead > -1);

服务器双面:

out.writeInt(data.length);   //DataOutputStream
//for(int i = 0;i < data.length;i++)
//{
//  out.writeByte(data[i]);
//}
out.write(data, 0, data.length);

使用已注释掉的替代方案完全没有区别。

1 个答案:

答案 0 :(得分:1)

您正在编写byte[]并将其读入byte[],但一次只读取一个字节,这意味着对文件中的每个字节调用一次操作系统。我建议一次阅读byte[]。例如使用readFully

int fileSize = Network.in.readInt(); //DataInputStream
byte[] data = new byte[fileSize];
Network.in.readFully(data);

如果你需要逐步看到它,你可以做到

for (int start = 0; start < fileSize; start += 8192) {
    Log.info("Downloading: " + (start / 1024) + " KB / " + (fileSize / 1024) + " KB");
    Network.in.readFully(data, start, Math.min(fileSize - start, 8192));
}