我正在使用 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/