通过封闭的websocket连接发送数据时,防止应用程序崩溃

erg*_*gen 0 c# websocket asp.net-core asp.net-core-1.0

ASP.NET Core应用程序在客户端使用websocket连接,在服务器端使用Microsoft.AspNetCore.WebSockets.Server 0.1.0(nuget上的最新稳定版本).简单的发送代码是

await _ws.SendAsync(new ArraySegment<byte>(arrbr), WebSocketMessageType.Text, true, ctk); 
Run Code Online (Sandbox Code Playgroud)

问题是这条线在关闭连接时抛出错误.如果进程成功,我希望该方法返回一个布尔值.我已经检查连接是否打开如下:

_ws.State == WebSocketState.Open 
Run Code Online (Sandbox Code Playgroud)

但是,如果用户已拔下网络电缆或断开其设备(几乎所有情况除了关闭浏览器),这都不起作用.

作为额外的,我不知道如何模拟两个客户端之一的网络连接丢失,我认为WebSocketState是只读的,请警告我,如果我错了,我不认为更短的ping会解决这个问题.
我有两个想法:

  1. 我可以在try catch块中使用发送者代码.(我不习惯在生产代码中使用try catch)

  2. 我可以在客户端设置间隔,并向服务器询问"对我来说什么是新的".我觉得这很糟糕,因为它远不是一个websocket(更接近http).

有没有办法解决这个问题而不使用try catch?我知道这不是一个合格的问题,而是一个合格的问题.如果需要,我可以分享完整的代码.

更新1

使用服务器端日志记录后:
虽然消息在生产环境中运行良好,但我通过拔下网络电缆并将数据发送到客户端来断开客户端连接.我使用try catch而没有捕获.然后我得到这个错误.
这意味着我无法通过使用try catch来检测丢失的连接.我想我可以通过处理这个投掷来解决这个问题.
我该如何处理这个错误?

UPDATE2

我注意到"异步空虚方法的例外不能被Catch捕获"和"它可以在catch中使用await",因为c#6 链接但是我无法捕获.如果我不能以这种方式修复,
我可能会尝试同步运行await _ws.SendAsync(new ArraySegment<byte>(arrbr), WebSocketMessageType.Text, true, ctk).runsynchronously();

UPDATE3

同步运行没有帮助.使用try catch没有区别.结果提问,asp.net核心websocket如何ping

UPDATE4

使用Microsoft.aspnetcore.websockets.server 0.1.0时的日志文件

fail: Microsoft.AspNetCore.Server.Kestrel[13] Connection id "0HL1940BSEV8O": An unhandled exception was thrown by the application. System.IO.IOException: Unexpected end of stream at Microsoft.AspNetCore.WebSockets.Protocol.CommonWebSocket.<EnsureDataAvailableOrReadAsync>d__38.MoveNext()
使用Microsoft.aspnetcore.websockets 1.0.0时的日志文件 fail: Microsoft.AspNetCore.Server.Kestrel[13] Connection id "0HL19H5R4CS21": An unhandled exception was thrown by the application. System.Net.WebSockets.WebSocketException (0x80004005): The remote party closed the WebSocket connection without completing the close handshake. ---> System.IO.IOException: Error -4077 ECONNRESET connection reset by peer ---> Microsoft.AspNetCore.Server.Kestrel.Internal.Networking.UvException: Error -4077 ECONNRESET connection reset by peer

Ita*_*cer 6

我可能会遗漏一些东西,但为什么不能将发送操作包装bool在以下列方式返回的方法中:

private async Task<bool> DoSend()
{
    bool success = true;

    try
    {
        await _ws.SendAsync(new ArraySegment<byte>(arrbr), WebSocketMessageType.Text, true, ctk);
    }
    catch (Exception ex)
    {
        // Do some logging with ex
        success = false;
    }

    return success;
}
Run Code Online (Sandbox Code Playgroud)

我还建议阅读有关Async All The Way的内容,它应该清除一些混淆async void,async Taskasync Task<T>