T
T
TheTalion2016-09-23 20:10:35
C++ / C#
TheTalion, 2016-09-23 20:10:35

WebSocket server is not keeping connection with client, how to keep connection?

Good day.
Initial data:
Websocket server (console application);
Websocket client (unit application).
This is how the websocket server looks like (I took a simple publicly available websocket as an example):

class Program
    {
        static void Main(string[] args)
        {
            TcpListener l_Listener = new TcpListener(IPAddress.Loopback, 8181);
            l_Listener.Start();
            while (true)
            {
                using (TcpClient l_Client = l_Listener.AcceptTcpClient())
                using (NetworkStream l_Stream = l_Client.GetStream())
                {
                    var l_headers = new Dictionary<string, string>();
                    string l_line = string.Empty;
                    while ((l_line = ReadLine(l_Stream)) != string.Empty)
                    {
                        var tokens = l_line.Split(new char[] { ':' }, 2);
                        if (!string.IsNullOrWhiteSpace(l_line) && tokens.Length > 1)
                        {
                            l_headers[tokens[0]] = tokens[1].Trim();
                        }
                    }

                    string l_secKey = l_headers["Sec-WebSocket-Key"];
                    string l_responseSecKey = ComputeWebSocketHandshakeSecurityHash09(l_secKey);

                    string l_response =
                        "HTTP/1.1 101 Switching Protocols" + Environment.NewLine +
                        "Upgrade: websocket" + Environment.NewLine +
                        "Connection: Upgrade" + Environment.NewLine +
                        "Sec-WebSocket-Accept: " + l_responseSecKey + Environment.NewLine + Environment.NewLine; 

                    var l_bufferedResponse = Encoding.UTF8.GetBytes(l_response);
                    l_Stream.Write(l_bufferedResponse, 0, l_bufferedResponse.Length);
                }
            }
        }

        public static string ComputeWebSocketHandshakeSecurityHash09(string secWebSocketKey)
        {
const string c_MagicKey = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
            string secWebSocketAccept = null; ;
            string l_combinedKey = secWebSocketKey + c_MagicKey;

            SHA1 l_Sha1Crypto = new SHA1CryptoServiceProvider();
            byte[] l_sha1Hash = l_Sha1Crypto.ComputeHash(Encoding.UTF8.GetBytes(l_combinedKey));
            secWebSocketAccept = Convert.ToBase64String(l_sha1Hash);

            return secWebSocketAccept ?? String.Empty;
        }

        static string ReadLine(Stream stream)
        {
            var l_Sb = new StringBuilder();
            var l_buffer = new List<byte>();
            while (true)
            {
                l_buffer.Add((byte)stream.ReadByte());
                string l_line = Encoding.ASCII.GetString(l_buffer.ToArray());
                if (l_line.EndsWith(Environment.NewLine))
                {
                    return l_line.Substring(0, l_line.Length - 2);
                }
            }
        }
    }

The fact is that the handshake successfully occurs and then the connection is simply broken. How to keep the connection, I do not quite understand? The client gets an error like this: "WebSocket Close : The header part of a frame cannot be read from the data source.", and the time of the error: "WebSocket Error : An exception has occurred while receiving a message". Just a handshake happens, and after that the connection is broken. I think that the point is that the server does not hold the connection, but I don’t understand how to implement this hold. Please help.
Thanks in advance for advice and tips.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg Tsilyurik, 2016-09-23
@TheTalion

The client gets an error like this:

The fashionable name WebSocket means at least 3 (or 4?) different protocols: 75, 76, 07 (see WebSocket ).
Since you took the server code 1st that caught your eye, and the client code (I guess) in the same way from another example, they most likely simply do not understand each other.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question