简体   繁体   中英

WebSocket connection is closing

I'm a beginner with the WebSocket API. I'm trying to connect to my server locally but I'm obtaining the connection closed message. Can anyone tell me what I am doing wrong?

That's my code:

Server

using System.Net.Sockets;
using System.Net;
using System.IO;
using System;
class Program
{
    static void Main(string[] args)
    {
        var listener = new TcpListener(IPAddress.Loopback, 8181);
    listener.Start();
    while (true)
    {
        Console.WriteLine("Listening...");
        using (var client = listener.AcceptTcpClient())
        using (var stream = client.GetStream())
        using (var reader = new StreamReader(stream))
        using (var writer = new StreamWriter(stream))
        {

            string line = null, key = "", responseKey = "";
            string MAGIC_STRING = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
            while (line != "")
            {
                line = reader.ReadLine();
                if (line.StartsWith("Sec-WebSocket-Key:"))
                {
                    key = line.Split(':')[1].Trim();
                }
            }

            if (key != "")
            {
                key += MAGIC_STRING;
                using (var sha1 = SHA1.Create())
                {
                    responseKey = Convert.ToBase64String(sha1.ComputeHash(Encoding.ASCII.GetBytes(key)));
                }
            }

            // send handshake to the client
            writer.WriteLine("HTTP/1.1 101 Web Socket Protocol Handshake");
            writer.WriteLine("Upgrade: WebSocket");
            writer.WriteLine("Connection: Upgrade");
            writer.WriteLine("WebSocket-Origin: http://localhost:8080");
            writer.WriteLine("WebSocket-Location: ws://localhost:8181/websession");
            if (!String.IsNullOrEmpty(responseKey))
                writer.WriteLine("Sec-WebSocket-Accept: " + responseKey);
            writer.WriteLine("");
            Console.ReadLine();
            writer.Flush();

        }//using
        Console.WriteLine("Finished");
    }//while

    }
}

The Client

     <!DOCTYPE HTML>
       <html>
       <head><title></title>
          <script type="text/javascript">

       function WebSocketTest() {
          var msg = document.getElementById("msg");
            if ("WebSocket" in window) {
             msg.innerHTML="WebSocket is supported by your Browser!";
        // Let us open a web socket
        var ws = new WebSocket("ws://localhost:8181/websession");
        ws.onopen = function () {
            // Web Socket is connected, send data using send()
             msg.innerHTML="connection open";
            //ws.send("Message to send");
            //msg.innerHTML="Message is sent...";
        };
        ws.onclose = function () {
            // websocket is closed.
            msg.innerHTML = "Connection is closed...";
        };

        ws.onerror = function(error){
            console.log('Error detected: ' + error);
        };
        ws.onmessage = function (evt) {
            var received_msg = evt.data;
            msg.innerHTML="Message is received...";
        };

    }
    else {
        // The browser doesn't support WebSocket
        msg.innerHTML="WebSocket NOT supported by your Browser!";
    }
   }
   </script>
     </head>
       <body>
       <div id="sse">
        <a href="javascript:WebSocketTest()">Run WebSocket</a><br />
         <p id="msg"></p>
       </div>
        </body> 
           </html>

Any solution would be appreciated and thank you :)

That is not a valid web-socket response under any specification. The initial web-socket response always requires you to crunch some numbers as part of the response headers, to prove you're a web-socket server. Which headers to read and write, and what crunching to do, depends on the version of web-sockets (hibi/hixie 76/rfc). It actually looks like your server is using the headers of a client .

For example, a RFC6455 (13) response would start:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: {crunch some numbers}

Note that a Hixie-76 response is different, and there are bits in the above that I have omitted.

From the RFC6455 specification :

To prove that the handshake was received, the server has to take two pieces of information and combine them to form a response. The first piece of information comes from the |Sec-WebSocket-Key| header field in the client handshake:

  Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== 

For this header field, the server has to take the value (as present in the header field, eg, the base64-encoded [RFC4648] version minus any leading and trailing whitespace) and concatenate this with the Globally Unique Identifier (GUID, [RFC4122]) "258EAFA5-E914-47DA- 95CA-C5AB0DC85B11" in string form, which is unlikely to be used by network endpoints that do not understand the WebSocket Protocol. A SHA-1 hash (160 bits) [FIPS.180-3], base64-encoded (see Section 4 of [RFC4648]), of this concatenation is then returned in the server's handshake.

After the javascript code connects to the webserver. C# runs through all using statements and prints all the lines to your file after which all using statements are closed and thus the generated client is disposed, which closes the connection.
A quick (but dirty) fix for this problem is to add "Console.Readline" at the end of the using statements. Be carefull with this though, your process will hang!
For more information about TcpClients accepting clients, go to msdn .
Notice that the given example there, only allows one connection at a time.
Last remark: there exist libraries for accepting websocket connections like Marc suggested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM