我想将字节直接从 TCP 套接字流式传输到磁盘上的文件。在 Java 中,可以使用 NIO channel ,特别是 SocketChannel
和 FileChannel
。引用 FileChannel#transferFrom(...)
:
This method is potentially much more efficient than a simple loop that reads from the source channel and writes to this channel. Many operating systems can transfer bytes directly from the source channel into the filesystem cache without actually copying them.
显然,我可以只编写标准的“复制循环”来读取和写入字节,甚至可以利用异步 I/O 来最大程度地减少等待。这是否可以与 Java 正在利用的平台 native 功能相媲美,还是有其他方法?
最佳答案
您可以使用 NetworkStream
读取数据, 然后使用 CopyTo
将数据写入 FileStream 的扩展方法。
.NET4 之前的手动方法:How do I save a stream to a file in C#?
对于发送,有一个Socket.SendFile
直接发送文件的方法,利用 Win32 TransmitFile
方法。不幸的是,没有相应的 Socket.ReceiveFile
方法或 ReceiveFile
Win32 API。
关于c# - .NET 等同于 Java FileChannel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11471536/