1
votes

I need to launch websocket server for javascript-based crm application. I study this example: Create "Hello World" WebSocket example but I can't established connection. Program throws an exception in

var key = headerResponse.Replace("ey:", "`")
                              .Split('`')[1]                     // dGhlIHNhbXBsZSBub25jZQ== \r\n .......
                              .Replace("\r", "").Split('\n')[0]  // dGhlIHNhbXBsZSBub25jZQ==
                              .Trim();

Frame sending from client looks as follows:

GET / HTTP/1.1 Host: localhost:9801 Connection: keep-alive Cache-Control: max-age=0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8 User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22 Accept-Encoding: gzip,deflate,sdch Accept-Language: pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4 Accept-Charset: ISO-8859-2 ,utf-8;q=0.7,*;q=0.3

The key part of frame is missing on any browser. How to resolve that?

1
What does the exception say?SLaks
Please include newlines in the headers.SLaks
Error message: "Index was outside the bounds of the array". The 'key' part of frame doesn't exists so the key cant be parsed from string. This key is neccessary?Adam Mrozek

1 Answers

0
votes

The way you are doing it seems a little bit unsave in regards to exceptions. Try to prevent this by validating the value you received. I can't say where your problem exactly is but this should fix your

Index was outside the bounds of the array

    string key = "";
    if (string.IsNullOrEmpty(headerResponse)) 
    {
        //No header response... handle it ;)
    }
    var replacedString = headerResponse.Replace("ey:", "`");
    string[] splitted = replacedString.Split('`');
    if (splitted.Length > 1)
    {
        string replaced2 = splitted[1].Replace("\r", "");
        string[] splitted2 = replaced2.Split('\n');
        if (splitted2.Length > 0)
        {
            key = splitted2[0].Trim();
        }
        else 
        {
            // '\n' not found
        }
    }
    else 
    {
        // '`' not found
    }

    if (string.IsNullOrEmpty(key))
    {
        //do error correction
    }
    else 
    {
        //everything is fine
    }