Hyn*_*rix 2 c# sockets tcp windows-phone-8
我使用a 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");
}
Run Code Online (Sandbox Code Playgroud)
这个示例代码有什么问题?
据推测,客户端正在使用带有连接保持活动的HTTP 1.1 - 因此它不会关闭流.您正在等待客户端发送更多数据,但客户端无意发送任何更多数据,因为它已为该请求"完成".
您应该使用HTTP请求中的内容长度来了解要尝试接收的数据量 - 并使用超时来避免在行为不正常的客户端的情况下永远等待.
| 归档时间: |
|
| 查看次数: |
1557 次 |
| 最近记录: |