Detect if the other end of a WebSocket has disconnected

In a previous post I showed how you can check if the other end of a TcpClient connection is unexpectedly disconnected.

I was migrating my game server from TcpClient to WebSockets, so I could host on a simple Azure Web app instead of having to pay for a virtual machine with additional ports open, when I realised I needed to be able to do the same thing or WebSockets.

public async Task<bool> GetIsAliveAsync()
{
	if (IsDisposed) return false;
	if (Client.State != WebSocketState.Open) return false;
	if (Client.CloseStatus is not null) return false;

	byte[] buffer = Array.Empty<byte>();
	try
	{
		await Client.SendAsync(buffer, WebSocketMessageType.Text, endOfMessage: false, CancellationToken.None);
		bool isAlive = (Client.State == WebSocketState.Open && Client.CloseStatus is null);
		return isAlive;
	}
	catch (IOException)
	{
		return false;
	}
	catch (SocketException)
	{
		return false;
	}
	catch (OperationCanceledException)
	{
		return false;
	}
}

It’s a bit of a cut-down version of my code because I am doing some other things in there too, but it should do the trick!

Comments

Leave a Reply

Your email address will not be published.