Getting data correctly using StreamSocket

I am using StreamSocketListener

to receive data on Windows Phone 8 (acting as server) sent by HTTP POST client. I can get the data, but when all the data is read, the method DataReader.LoadAsync()

hangs until I manually remove the client connection:

_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?

+2


source to share


1 answer


Presumably the client is using HTTP 1.1 with a keep-alive connection - so it doesn't close the stream. You expect the client to send more data, but the client does not intend to send more data because it is "made" for this request.



You should use the length of the content from the HTTP request to find out how much data to try and use a timeout to avoid waiting forever in case of bad client behavior.

+6


source







All Articles