使用StreamSocket挂起正确接收数据

时间:2013-10-06 08:17:16

标签: c# sockets tcp windows-phone-8

我正在使用StreamSocketListener接收HTTP POST客户端发送的Windows Phone 8(充当服务器)上的数据。我可以接收数据,但是当读取所有数据时,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");
}

此示例代码有什么问题?

1 个答案:

答案 0 :(得分:6)

据推测,客户端正在使用带有连接保持活动状态的HTTP 1.1 - 因此它不会关闭流。您正在等待客户端发送更多数据,但客户端无意发送任何更多数据,因为它已为该请求“完成”。

您应该使用HTTP请求中的内容长度来了解尝试接收的数据量 - 并使用超时来避免在行为不正常的客户端中永远等待。