我有以下代码:
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从客户端传递到服务器)。
答案 0 :(得分:2)
基本上John回答了
WebSocketReceiveResult.Count Property
指示WebSocket接收的字节数。
在两种情况下,计数可以为0:
WebSocket收到一条空消息。在这种情况下,CloseStatus 属性为“无”。
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
教程和一些防弹(典型)设计