【问题标题】:C# Websocket The remote party closed the WebSocket connection without completing the close handshakeC# Websocket 远程方未完成关闭握手就关闭了WebSocket连接
【发布时间】:2021-02-20 17:26:18
【问题描述】:

您好,我目前正在为我的基本站点实现一个 websocket 组件。我正在运行 .NET Core 3.1 HTTP 侦听器来提供 html,我被实现 websockets 难住了。

我之前在 C# 中使用过 TCP,并且了解一切的流程,但 websockets 对我来说是一个新事物。这是接受 websockets 的 C# 代码

        [Route("/socket", "GET")]
        public static async Task upgrade(HttpListenerContext c)
        {
            if (!c.Request.IsWebSocketRequest)
            {
                c.Response.StatusCode = 400;
                c.Response.Close();
                return;
            }

            try
            {
                var sock = (await c.AcceptWebSocketAsync(null)).WebSocket;
                byte[] buff = new byte[1024];
                var r = await sock.ReceiveAsync(buff, System.Threading.CancellationToken.None);
            }
            catch (Exception x) 
            {
                Console.WriteLine($"Got exception: {x}");
            }
           
            //WebSocketHandler.AddSocket(sock);
            
        }

我已将var r = await sock.ReceiveAsync(buff, System.Threading.CancellationToken.None); 添加到此函数中,因为最初我在 WebSocketHandler 类中遇到异常,因此我将代码移至一个函数进行测试。

这里是客户端:

  <script>
    let socket = new WebSocket("ws://localhost:3000/socket");

    socket.onopen = function (event) {
      console.log("[ OPENED ] - Opened Websocket!");
    };

    socket.onclose = function (event) {
      console.log("[ CLOSED ] - Socket closed");
    };

    socket.onerror = function (error) {
      console.log("[ ERROR ] - Got websocket error:");
      console.error(error);
    };
    socket.onmessage = function (event) {
      // This function will be responsible for handling events
      console.log("[ MESSAGE ] - Message received: ");
      const content = JSON.parse(event.data);
      console.log(content);
    };

  </script>

这是客户端控制台中的输出:

Navigated to http://127.0.0.1:5500/index.html
index.html:556 [ OPENED ] - Opened Websocket!
index.html:569 [ CLOSED ] - Socket closed

这是来自 C# 服务器的异常:

Got exception: System.Net.WebSockets.WebSocketException (997): The remote party closed the WebSocket connection without completing the close handshake.
   at System.Net.WebSockets.WebSocketBase.WebSocketOperation.Process(Nullable`1 buffer, CancellationToken cancellationToken)
   at System.Net.WebSockets.WebSocketBase.ReceiveAsyncCore(ArraySegment`1 buffer, CancellationToken cancellationToken)
   at SwissbotCore.HTTP.Routes.UpgradeWebsocket.upgrade(HttpListenerContext c) in C:\Users\plynch\source\repos\SwissbotCore\SwissbotCore\HTTP\Routes\UpgradeWebsocket.cs:line 29

如果需要,我可以提供客户端发送的 http 请求,但我对此完全感到困惑,任何帮助将不胜感激。

【问题讨论】:

  • 传递给 onClose 函数的事件可能包含一些信息。但它可能只是一个代码 1006

标签: javascript c# .net .net-core websocket


【解决方案1】:

您可能想阅读Section 1.4 in RFC 6455 中的关闭握手 以及Section 7.1.1 in RFC 6455 中的关闭 WebSocket 连接

基本上,在终止套接字之前,您需要让 WebSocket 端点知道您将要关闭套接字。

对于您的服务器端,您可能应该遇到此异常,因为这也可能在生产场景中发生网络问题时发生。

【讨论】:

【解决方案2】:

我不知道为什么,但是,如果您将 try 块中的代码更改为:

try
{
   var sock = (await c.AcceptWebSocketAsync(null)).WebSocket;
   byte[] buff = new byte[1024];
   
   await Listen(sock);
}
catch (Exception x) 
{
   Console.WriteLine($"Got exception: {x}");
}

private async Task Listen(WebSocket sock)
{
   return new Task(async () => 
   {
      while(sock.State == WebSocketState.Open)
      {
         var r = await sock.ReceiveAsync(buff, System.Threading.CancellationToken.None);
      }
   });
}

一切都会好起来的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-06
    • 2012-08-08
    • 2019-07-19
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    相关资源
    最近更新 更多