Reputation: 93
I can able to chat if I continuously chat. If I leave for a 2-3 mins WebSocket connection close without handshake error message I am getting I don't know how to handle.
Can anyone please help how to handle the exception.i have attached the crash log and here is my code.
click thumbnail to see the full error
public async void ConnectToServerAsync()
{
await client.ConnectAsync(new Uri("ws://api.testurl.com/ws"), CancellationToken.None);
UpdateClientState();
await Task.Factory.StartNew(async () =>
{
Refresh();
while (client.State == WebSocketState.Open)
{
WebSocketReceiveResult result;
var message = new ArraySegment<byte>(new byte[4096]);
var allBytes = new List<byte>();
do
{
result = await client.ReceiveAsync(message, CancellationToken.None);
for (int i = 0; i < result.Count; i++)
{
allBytes.Add(message.Array[i]);
}
} while (!result.EndOfMessage);
try
{
Debug.WriteLine("End of Message2 :" + result.EndOfMessage);
Debug.WriteLine("All Bytes :" + allBytes.ToString());
// Optional step to convert to a string (UTF-8 encoding).
var serialisedMessae = Encoding.UTF8.GetString(allBytes.ToArray(), 0, allBytes.Count);
var msg = JsonConvert.DeserializeObject<List<ChatModel>>(serialisedMessae);
Debug.WriteLine("Message Count :" + msg.Count);
if (Chatlist.Count != msg.Count)
{
Chatlist.Clear();
foreach (var item in msg)
{
var details = new ChatModel()
{
Message = item.Message,
MessageFrom = item.MessageFrom,
MessageTo = item.MessageTo,
RoomId = item.RoomId,
_id = item._id,
TimeStamp = item.TimeStamp.ToLocalTime()
};
Chatlist.Insert(0, details);
}
}
}
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}");
}
}
Upvotes: 1
Views: 4877
Reputation: 3276
Ideally when you've completed the work with your WebSocket you need to close it by using something like the following:
await client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "closing websocket", CancellationToken.None);
That should solve the problem. Or simply do not re-create the WebSocket
once it's been opened. I couldn't see the client creation code in your post above, but I'm making a bit of an assumption that for whatever reason it's trying to re-make the WebSocket
, but it already has an existing connection, and as such throws that error.
Upvotes: 1