我使用.NET Core 3.0JsonDocument.Parse(ReadOnlyMemory<Byte>, JsonReaderOptions)将WS消息()解析byte[]为JSON,但它抛出一个异常,如下所示:
'0x00' is invalid after a single JSON value. Expected end of data. LineNumber: 0 | BytePositionInLine: 34.
Run Code Online (Sandbox Code Playgroud)
这是我的中间件片段代码:
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}");
}
}
Run Code Online (Sandbox Code Playgroud)
正如评论中提到的,您犯了一些错误。最大的问题之一是分配内存(从长远来看会导致分配和垃圾回收,这是 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}");
}
}
Run Code Online (Sandbox Code Playgroud)
您需要对其进行切片,以便 Json 解析器不会读取超出 JSON 字符串末尾的内容。
| 归档时间: |
|
| 查看次数: |
4331 次 |
| 最近记录: |