.NET Core JsonDocument.Parse(ReadOnlyMemory <Byte>,JsonReaderOptions)无法从WebSocket ReceiveAsync解析

时间:2019-06-19 07:43:03

标签: c# asp.net-core

我使用.NET Core 3.0的JsonDocument.Parse(ReadOnlyMemory<Byte>, JsonReaderOptions)将WS消息(byte[])解析为JSON,但它引发了如下异常:

'0x00' is invalid after a single JSON value. Expected end of data. LineNumber: 0 | BytePositionInLine: 34.

这是我的中间件代码段:

WebSocket ws = await context.WebSockets.AcceptWebSocketAsync();
byte[] bytes = new byte[1024 * 4];
ArraySegment<byte> buffer = new ArraySegment<byte>(bytes);

while (ws.State == WebSocketState.Open)
{
       try
       {
             WebSocketReceiveResult request = await ws.ReceiveAsync(bytes, CancellationToken.None);
             switch (request.MessageType)
             {
                     case WebSocketMessageType.Text:
                             string msg = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
                             json = new ReadOnlyMemory<byte>(bytes);
                             JsonDocument jsonDocument = JsonDocument.Parse(json);
                             break;
                     default:
                             break;
             }
       }
       catch (Exception e)
       {
             Console.WriteLine($"{e.Message}\r\n{e.StackTrace}");
       }
 }

1 个答案:

答案 0 :(得分:0)

如评论中所述,您犯了一些错误。最大的问题之一就是分配内存(从长远来看,这会导致分配和gc,这是Memory / Span API想要避免的事情)。第二个原因是,您没有对数据进行切片,因为您的有效负载小于缓冲区大小。

我对代码做了一些修复

WebSocket ws = await context.WebSockets.AcceptWebSocketAsync();
// Don't do that, it allocates. Beats the main idea of using [ReadOnly]Span/Memory
// byte[] bytes = new byte[1024 * 4];

// We don't need this either, its old API. Websockets support Memory<byte> in an overload
// ArraySegment<byte> buffer = new ArraySegment<byte>(bytes);

// We ask for a buffer from the pool with a size hint of 4kb. This way we avoid small allocations and releases
// P.S. "using" is new syntax for using(disposable) { } which will
// dispose at the end of the method. new in C# 8.0
using IMemoryOwner<byte> memory = MemoryPool<byte>.Shared.Rent(1024 * 4);

while (ws.State == WebSocketState.Open)
{
    try
    {
        ValueWebSocketReceiveResult request = await ws.ReceiveAsync(memory.Memory, CancellationToken.None);
        switch (request.MessageType)
        {
            case WebSocketMessageType.Text:
                // we directly work on the rented buffer
                string msg = Encoding.UTF8.GetString(memory.Memory.Span);
                // here we slice the memory. Keep in mind that this **DO NOT ALLOCATE** new memory, it just slice the existing memory
                // reason why it doesnt allocate is, is that Memory<T> is a struct, so its stored on the stack and contains start 
                // and end position of the sliced array
                JsonDocument jsonDocument = JsonDocument.Parse(memory.Memory.Slice(0, request.Count));
                break;
            default:
                break;
        }
    }
    catch (Exception e)
    {
        Console.WriteLine($"{e.Message}\r\n{e.StackTrace}");
    }
}

您需要对其进行切片,以便Json解析器不会在JSON字符串的末尾读取内容。