【问题标题】:Issue while reading from Stream in UWP从 UWP 中的 Stream 读取时出现问题
【发布时间】:2018-12-13 06:33:05
【问题描述】:

我有一个使用 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!

有人有想法吗?

最好的问候,克里斯坦

【问题讨论】:

    标签: c# .net uwp stream network-programming


    【解决方案1】:

    首先,我无法使用官方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);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2015-08-18
      • 2015-07-17
      • 2021-12-20
      • 1970-01-01
      • 2021-05-24
      • 1970-01-01
      • 1970-01-01
      • 2015-11-28
      • 1970-01-01
      相关资源
      最近更新 更多