[英]Websockets convert byte[] to string
我有以下代碼:
Console.WriteLine("New Socket connection opened");
var buffer = new byte[1024 * 4];
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
Console.WriteLine("New message received : "+ Encoding.UTF8.GetString(buffer));
}
當我向客戶發送Hello
,我可以看到Hello?????????????
在控制台上。 顯然,這意味着我有一個大小為1024 * 4
的緩沖區,其中前幾個字節由Hello
占用。 我如何trim
字符串(最終,我想將JSON從客戶端傳遞到服務器)。
約翰基本上回答了這個
WebSocketReceiveResult.Count屬性
指示WebSocket接收的字節數。
在兩種情況下,計數可以為0:
WebSocket收到一條空消息。 在這種情況下,CloseStatus屬性為None。
WebSocket收到了來自遠程端點的關閉消息。 在這種情況下,CloseStatus屬性設置為除None以外的其他值。
GetString(Byte [],Int32,Int32)
public virtual string GetString (byte[] bytes, int index, int count);
在派生類中重寫時,將指定字節數組中的字節序列解碼為字符串。
- bytes
Byte[]
包含要解碼的字節序列的字節數組。- index
Int32
要解碼的第一個字節的索引。- count
Int32
要解碼的字節數。
所以你需要這樣的東西
Console.WriteLine("New message received : "+ Encoding.UTF8.GetString(buffer,0,Result.Count));
但是,它卻很大。 還有更多出錯的地方,我會認真建議獲得一個好的WebSocket
教程和一些防彈(典型)設計
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.