C#C
C#2y ago
11 replies
knut.wannheden

Best practice reading from `Socket` / `NetworkStream`?

I've got a C# application in which I want to read data from a Unix domain socket (on the sending side I have a Java application which sends buffered data). I want to read all data into a MemoryStream, as I subsequently want to parse that using CborReader (unfortunately I didn't find any way getting the CborReader itself to read the data directly from the socket).

Now, to my question: I can't figure out what the best practice should be for fully reading the data from the Unix domain socket into a MemoryStream. My tests indicate that I can't rely solely on NetworkStream.DataAvailable but also need to call Socket.Poll(), so I've come up with the following code:

    private static MemoryStream ReadFully(Socket socket, NetworkStream stream)
    {
        var memoryStream = new MemoryStream();
        var buffer = new byte[8192];
        while (socket.Poll(TimeSpan.FromMilliseconds(100), SelectMode.SelectRead))
        {
            while (stream.DataAvailable)
            {
                var bytesRead = stream.Read(buffer, 0, buffer.Length);
                memoryStream.Write(buffer, 0, bytesRead);
            }
        }
        memoryStream.Position = 0;
        return memoryStream;
    }

Does this make sense or is there a better / more idiomatic way?
Was this page helpful?