Correctly receiving data using StreamSocket hangs

I am using a StreamSocketListener to receive data on a Windows Phone 8 (acting as server) sent by a HTTP POST client. I can receive the data but when all data is read the DataReader.LoadAsync() method hangs until I manually cancel the connection from the client:

_streamSocket = new StreamSocketListener();
_streamSocket.ConnectionReceived += _streamSocket_ConnectionReceived;
await _streamSocket.BindServiceNameAsync("30000");


private async void _streamSocket_ConnectionReceived(StreamSocketListener sender,
        StreamSocketListenerConnectionReceivedEventArgs args)
{
    using (IInputStream inStream = args.Socket.InputStream)
    {
        DataReader reader = new DataReader(inStream);
        reader.InputStreamOptions = InputStreamOptions.Partial;

        do
        {
            numReadBytes = await reader.LoadAsync(1 << 20);  // "Hangs" when all data is read until the client cancels the connection, e.g. numReadBytes == 0
            System.Diagnostics.Debug.WriteLine("Read: " + numReadBytes);

            // Process data
            if (numReadBytes > 0)
            {
                byte[] tmpBuf = new byte[numReadBytes];
                reader.ReadBytes(tmpBuf);
            }
        } while (numReadBytes > 0);
    }

    System.Diagnostics.Debug.WriteLine("Finished reading");
}

What's wrong with this sample code?

Jon Skeet
people
quotationmark

Presumably the client is using HTTP 1.1 with connection keep-alive - so it's not closing the stream. You're waiting for the client to send more data, but the client has no intention of sending any more data because it's "done" for that request.

You should use the content length from the HTTP request to know how much data to try to receive - and use a timeout to avoid waiting forever in the case of a badly-behaved client.

people

See more on this question at Stackoverflow