我正在使用C#中的ClientWebSocket进行聊天。我可以接收消息,但可以接收2个4096字节的数据包。如何一举获得全部?
代码
public async void ConnectToServerAsync()
{
ClientWebSocket client = new ClientWebSocket();
await client.ConnectAsync(new Uri("ws://local123:ws"), CancellationToken.None);
UpdateClientState();
await Task.Factory.StartNew(async () =>
{
Refresh();
WebSocketReceiveResult result;
var buf = new byte[8192];
var message = new ArraySegment<byte>(buf, 0, buf.Length);
result = await client.ReceiveAsync(message, CancellationToken.None);
//var messageBytes = message.Skip(message.Offset).Take(result.Count).ToArray();
string serialisedMessae = Encoding.UTF8.GetString(buf,0,result.Count);
try
{
var msg = JsonConvert.DeserializeObject<List<ChatModel>>(serialisedMessae);
Debug.WriteLine(msg.Count);
if (Chatlist.Count != msg.Count)
{
Chatlist.Clear();
foreach (var chatmsg in msg)
{
var details = new ChatModel()
{
Message = chatmsg.Message,
MessageFrom = chatmsg.MessageFrom,
MessageTo = chatmsg.MessageTo,
RoomId = chatmsg.RoomId,
};
Chatlist.Insert(0, details);
}
}
else
{
}
}
catch (Exception ex)
{
Console.WriteLine($"Invalide message format. {ex.Message}");
}
}
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
void UpdateClientState()
{
OnPropertyChanged(nameof(IsConnected));
sendMessageCommand.ChangeCanExecute();
Console.WriteLine($"Websocket state {client.State}");
}
}
当我反序列化响应时。我可以在一个数据包中得到一个部分json,然后在另一个数据包中得到休息。如何一次获取整个json?