Websocket .net core detect when client looses internet connectivity #9053

@JocelyneElKhoury

Description

@JocelyneElKhoury

I am using websocket in .net core and my issue is that when the client is no longer connected to the internet his websocket connection closes but as per the server the client is still connected, i am not receiving any disconnection packet, in addition i am publishing the websocket on Azure and i have set the property WebSocket=ON and AlwaysOn=On. Please can you help me !

references:
https://github.com/aspnet/Docs/tree/master/aspnetcore/fundamentals/websockets/samples
https://code.msdn.microsoft.com/How-to-use-websocket-with-2c6d8b6e/sourcecode?fileId=172049&pathId=1358619959

i have the below server:

 public async Task Invoke(HttpContext context)
if (context.WebSockets.IsWebSocketRequest)
	SocketUserObject socketUser = new SocketUserObject();
	if (_webSocketLogic.IsAuthorizedUser(context, ref socketUser, _operation))
		var connection = await _webSocketHandler.OnConnected(context, socketUser, _operation);
		if (connection != null)
			await _webSocketHandler.ListenConnection(connection);
			context.Response.StatusCode = 404;
		context.Response.StatusCode = 404;
   public async Task ListenConnection(WebSocketConnection connection)
var buffer = new byte[BufferSize];
	while (connection.WebSocket.State == WebSocketState.Open)
		var result = await connection.WebSocket.ReceiveAsync(
			 buffer: new ArraySegment<byte>(buffer),
			 cancellationToken: CancellationToken.None);
		if (result.MessageType == WebSocketMessageType.Text)
			var message = Encoding.UTF8.GetString(buffer, 0, result.Count);
			await ReceiveAsync(connection, message, _operation2);
		else if (result.MessageType == WebSocketMessageType.Close)
			await OnDisconnected(connection, _operation2);
catch (Exception ex)
	_logging.TraceError(ex, _operation);
_logging.TraceLog(System.Reflection.MethodInfo.GetCurrentMethod(), _operation, "after State ", connection.WebSocket.State.ToString());
And I have added in the startup the below:

    var webSocketOptions = new WebSocketOptions()
        KeepAliveInterval = TimeSpan.FromSeconds(1),
        ReceiveBufferSize = 4 * 1024
    app.UseWebSockets(webSocketOptions);

I also tried adding this to the web.config file created on Azure from Kudu console:

  <system.webServer>
        <webSocket  enabled="true"   receiveBufferLimit="4194304"  pingInterval="00:01:00">
        </webSocket>
   </system.webServer>

and this is my client :

  public void StartReceiving(int modulo)
    RunWebSockets().GetAwaiter().GetResult();
  private async Task RunWebSockets()
    var client = new ClientWebSocket();
        client.Options.SetRequestHeader("id_handset", "1");
        await client.ConnectAsync(new Uri(url), CancellationToken.None);
        Console.WriteLine("Connected!");
        var sending = Task.Run(async () =&gt;
            string line;
            if (client.State == WebSocketState.Open)
                SocketOperation.Start(_socketOperation, client);
        var receiving = Receiving(client);
        await Task.WhenAll(sending, receiving);
    catch (Exception ex)
        if (client.State == WebSocketState.Open)
            await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
        SocketOperation.StopConsole();
        RunWebSockets().GetAwaiter().GetResult();
  private async Task Receiving(ClientWebSocket client)
    var buffer = new byte[1024 * 4];
    while (true)
        var result = await client.ReceiveAsync(new ArraySegment&lt;byte&gt;(buffer), CancellationToken.None);
        if (result.MessageType == WebSocketMessageType.Text)
            Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, result.Count));
        else if (result.MessageType == WebSocketMessageType.Close)
            await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
            SocketOperation.StopConsole();
            RunWebSockets().GetAwaiter().GetResult();
            //await client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
            break;

Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

  • ID: a3b0cac1-adc7-434c-d867-6e28e39bdae7
  • Version Independent ID: 762efeed-010e-f422-03d0-22d6681b2851
  • Content: WebSockets support in ASP.NET Core
  • Content Source: aspnetcore/fundamentals/websockets.md
  • Product: aspnet-core
  • GitHub Login: @Rick-Anderson
  • Microsoft Alias: tdykstra
  •