c# - 使用 StreamSocket 正确接收数据挂起

标签 c# sockets tcp windows-phone-8

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

这个示例代码有什么问题?

最佳答案

推测客户端正在使用 HTTP 1.1 和连接保持事件 - 所以它不会关闭流。您正在等待客户端发送更多数据,但客户端无意发送更多数据,因为该请求已“完成”。

您应该使用 HTTP 请求的内容长度来了解要尝试接收多少数据 - 并使用超时来避免在客户端行为不当的情况下永远等待。

关于c# - 使用 StreamSocket 正确接收数据挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19206804/

相关文章:

c - C中的多线程TCP服务器

linux - 如何为套接字打开 IPCOMP?

c# - 在步骤 C# 中将用户输入添加到数组?

c# - 如何正确使用 SqlDataReader?

c# - html 敏捷包 vs antixss

java - 有多少人可以连接到ServerSocket?

TCP 拥塞算法 - Tcp Westwood 或 Tcp westwood plus?

c# - 值之间的平滑过渡(缓入/缓出)

php - 我的PHP脚本无法连接到IRC服务器

c++ - 使用轮询的套接字响应超时