gpt4 book ai didi

c# - .NET Core JsonDocument.Parse(ReadOnlyMemory, JsonReaderOptions) 无法从 WebSocket ReceiveAsync 解析

转载 作者:行者123 更新时间:2023-12-02 00:17:11 27 4
gpt4 key购买 nike

我使用 .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}");
}
}

最佳答案

如评论中所述,您犯了一些错误。最大的一个是分配内存(从长远来看会导致分配和 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 字符串末尾的部分。

关于c# - .NET Core JsonDocument.Parse(ReadOnlyMemory<Byte>, JsonReaderOptions) 无法从 WebSocket ReceiveAsync 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56662515/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com