I want to stream bytes directly from a TCP socket to a file on disk. In Java, it’s possible to use NIO Channels, specifically SocketChannel and FileChannel. Quoting 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.
Obviously I can just write the standard “copy loop” to read and write the bytes, and even take advantage of asynchronous I/O to minimize waiting. Will that be comparable to the platform native functionality that Java is taking advantage of, or is there another approach?
You can read the data with a
NetworkStream, then use theCopyToextension method to write the data into a FileStream.A manual approach, pre .NET4: How do I save a stream to a file in C#?
For sending, there is a
Socket.SendFilemethod that directly sends a file, utilizing the Win32TransmitFilemethod. Unfortunately there is no correspondingSocket.ReceiveFilemethod orReceiveFileWin32 API.