DataReader访问数据问题

时间:2017-06-21 09:39:23

标签: c# datareader hololens

我想使用DataReader来读取客户端发送的消息。这是我的代码:

private async void Listener_ConnectionReceived(StreamSocketListener sender,
    StreamSocketListenerConnectionReceivedEventArgs args)
    {
        try 
        {
            using (DataReader reader = new DataReader(args.Socket.InputStream)) 
            {
                string receivedData;
                var count = await reader.LoadAsync((uint)reader.ReadInt32());
                receivedData = reader.ReadString(count);
                Debug.Log("Received : " + receivedData);
            }
        }
        catch (Exception e)
        {
            Debug.Log("Error: " + e.Message);
        }
    }

但是我收到此错误消息:操作尝试访问有效范围之外的数据(HRESULT异常:0x8000000B)任何想法?谢谢!

2 个答案:

答案 0 :(得分:0)

(uint)reader.ReadInt32()

此代码尝试在流的开头读取一个整数,指示正在发送的其余数据的长度。很可能,发件人没有正确填充该整数。请他们设置它。

答案 1 :(得分:0)

新代码,新状态,新错误:

private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
    {
        using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
        {
            using (var inputStream = stream.GetInputStreamAt(0))
            {

                try {

                    using (DataReader reader = new DataReader(args.Socket.InputStream)) {

                        reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                        reader.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;

                        await reader.LoadAsync((uint)stream.Size);

                        var receivedStrings = "";

                        uint bytesToRead = reader.ReadUInt32();
                        receivedStrings += reader.ReadString(bytesToRead) + "\n";

                        Debug.Log("Received : " + receivedStrings);

                    }
                }
                catch (Exception e) {
                    Debug.Log("Error: " + e.Message);
                }
            }
        }
    }

我现在收到此错误:

Error: The parameter is incorrect. 
count