最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - C# Websocket The remote party closed the WebSocket connection without completing the close handshake - Stack Overfl

programmeradmin2浏览0评论

Hello I'm currently implementing a websocket ponent to my very basic site. I'm running .NET Core 3.1 HTTP Listener for serving html, I've been stumped by implementing websockets.

I've worked with TCP in C# before and understand the flow of everything but websockets are a new thing to me. Here is the C# code for accepting websockets

        [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);
            
        }

I've added var r = await sock.ReceiveAsync(buff, System.Threading.CancellationToken.None); to this function because originally I was getting the exception in my WebSocketHandler class, so I moved the code to the one function to test.

Here is the client:

  <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>

Here is the output in the console for the client:

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

And here is the exception from the C# server:

Got exception: System.Net.WebSockets.WebSocketException (997): The remote party closed the WebSocket connection without pleting 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

I can provide the http requests that the client sends if need be but I am pletely stumped on this, any help will be greatly appreciated.

Hello I'm currently implementing a websocket ponent to my very basic site. I'm running .NET Core 3.1 HTTP Listener for serving html, I've been stumped by implementing websockets.

I've worked with TCP in C# before and understand the flow of everything but websockets are a new thing to me. Here is the C# code for accepting websockets

        [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);
            
        }

I've added var r = await sock.ReceiveAsync(buff, System.Threading.CancellationToken.None); to this function because originally I was getting the exception in my WebSocketHandler class, so I moved the code to the one function to test.

Here is the client:

  <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>

Here is the output in the console for the client:

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

And here is the exception from the C# server:

Got exception: System.Net.WebSockets.WebSocketException (997): The remote party closed the WebSocket connection without pleting 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

I can provide the http requests that the client sends if need be but I am pletely stumped on this, any help will be greatly appreciated.

Share Improve this question asked Nov 8, 2020 at 16:53 QuinchQuinch 1711 gold badge3 silver badges4 bronze badges 2
  • The event that is passed to your onClose function might have some information. But it is likely just a code 1006 – Peter Rasmussen Commented Dec 12, 2020 at 11:04
  • Server only read, and not send anything => The websocket is closed because there is no two-way data exchange – tqk2811 Commented May 30, 2024 at 3:55
Add a ment  | 

1 Answer 1

Reset to default 1

You might want to read up on The Close Handshake in Section 1.4 in RFC 6455 and also Close the WebSocket Connection in Section 7.1.1 in RFC 6455.

Essentially, you need to let the WebSocket endpoint know you are going to close the socket, before you terminate the socket.

For your server side, you should probably be catching this exception, as this can also happen in production scenarios when network issues occur.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论