我有一个使用 StreamSocket 的小型UWP应用。通过使用 socket.InputStream.AsStreamForRead()方法访问套接字。
这几乎适用于所有大小的传入数据(10字节至6,000字节)。但是,当使用带有缓冲区大小的重载时,套接字会在收到更多数据时挂起。因此,如果将缓冲区设置为4096,将不再接收6000字节。即使以10字节的块大小读取数据,它也不起作用。方法 ReadAsync 永远挂起。
我不确定这是否是错误。我希望我仍然可以接收数据。如果不是这样,我需要知道该缓冲区的默认大小或行为。
示例代码:
StreamSocket socket = InitSomewhere();
var readStream = socket.InputStream.AsStreamForRead(500);
var buffer = new byte[100]
readStream.ReadAsync(buffer, 0, 100) // Hangs here if received > 500!
有人有主意吗?
最诚挚的问候,克里斯坦
答案 0 :(得分:0)
首先,我无法使用StreamSocket官方样本重现此问题。
另一方面,您可以尝试使用DataReader类作为上述示例读取数据。
private async void OnConnection(
StreamSocketListener sender,
StreamSocketListenerConnectionReceivedEventArgs args)
{
DataReader reader = new DataReader(args.Socket.InputStream);
try
{
while (true)
{
// Read first 4 bytes (length of the subsequent string).
uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
if (sizeFieldCount != sizeof(uint))
{
// The underlying socket was closed before we were able to read the whole data.
return;
}
// Read the string.
uint stringLength = reader.ReadUInt32();
uint actualStringLength = await reader.LoadAsync(stringLength);
if (stringLength != actualStringLength)
{
// The underlying socket was closed before we were able to read the whole data.
return;
}
// Display the string on the screen. The event is invoked on a non-UI thread, so we need to marshal
// the text back to the UI thread.
NotifyUserFromAsyncThread(
String.Format("Received data: \"{0}\"", reader.ReadString(actualStringLength)),
NotifyType.StatusMessage);
}
}