且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

对Java套接字大文件传输

更新时间:2023-01-06 07:43:11

您说的没错,这是一个好办法做到这一点。它浪费内存和时间;它假定该文件的大小为32位;它假定整个文件装配到存储器;它假定整个文件被读取在一个读取;并且它直到整个文件已经被读取不发送任何东西。

You're right, this is a poor way to do it. It wastes both memory and time; it assumes the file size is 32 bits; it assumes the entire file fits into memory; it assumes the entire file is read in one read; and it doesn't send anything until the entire file has been read.

复制Java中的数据流的典型方法是这样的:

The canonical way to copy a stream in Java is this:

while ((count = in.read(buffer)) > 0)
{
  out.write(buffer, 0, count);
}

这将与你喜欢的,因此任何大小的文件,你可以拿出任何大小的缓冲区。使用相同的code两端,虽然你没有使用相同大小的缓冲区的两端。当你复制在网络上,你可能会认为1K或1.5K是***的大小,但可以俯瞰套接字发送的presence和接收缓冲区在内核中。当你考虑到这些可能是更好使用8K以上。

It will work with any size buffer you like and therefore with any size file you can come up with. Use the same code at both ends, although you don't have to use the same size buffer at both ends. As you're copying over a network you might think that 1k or 1.5k is the best size, but that overlooks the presence of the socket send and receive buffers in the kernel. When you take them into account it is probably better to use 8k or more.