简体   繁体   English

使用StreamSocket正确接收数据挂起

[英]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. 我正在使用StreamSocketListener来接收由HTTP POST客户端发送的Windows Phone 8(充当服务器)上的数据。 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: 我可以接收数据,但是当读取所有数据时, DataReader.LoadAsync()方法将挂起,直到我手动从客户端取消连接为​​止:

_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? 此示例代码有什么问题?

Presumably the client is using HTTP 1.1 with connection keep-alive - so it's not closing the stream. 假定客户端正在使用HTTP 1.1和连接保持活动状态-因此它不会关闭流。 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. 您应该使用HTTP请求中的内容长度来知道要尝试接收多少数据-并使用超时以避免在客户端行为不佳时永远等待。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM