简体   繁体   中英

C# Building Web Socket Server

I'm trying to build a WebSocket Server using C# i have been reading tutorials left right and centre to try and get this working.

So i'm using Advanced Rest Client (ARC) in in google chrome

to make the connection to my Server but it seems to hang at "Connecting to the remote server".

My Code for elevation to a WebSocket

Console.WriteLine("Connection Establised to: " + ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString());
// sets two streams
StreamWriter sWriter = new StreamWriter(client.GetStream(), Encoding.UTF8);
StreamReader sReader = new StreamReader(client.GetStream(), Encoding.UTF8);
// you could use the NetworkStream to read and write, 
// but there is no forcing flush, even when requested

Boolean bClientConnected = true;
String sData = null;

bool gotHeaders = false;
string headerBlock = "";
try
{
    while (!gotHeaders)
    {
        sData = sReader.ReadLine();
        headerBlock += sData + "\r\n";
        Console.WriteLine("Client << " + sData);
        if (headerBlock.Substring(headerBlock.Length - 4, 4) == "\r\n\r\n")
        {
            gotHeaders = true;
        }
    }
    string headerResponse = "HTTP/1.1 101 Switching Protocols\r\n"
    + "Connection: Upgrade\r\n"
    + "Upgrade: websocket\r\n"
    + "Sec-WebSocket-Accept: " + Convert.ToBase64String(
        SHA1.Create().ComputeHash(
            Encoding.UTF8.GetBytes(
                new Regex("Sec-WebSocket-Key: (.*)").Match(headerBlock).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
            )
        )
    ) + "\r\n\r\n";
    Console.WriteLine("Server >> HTTP/1.1 101 Switching Protocols\r\n"
    + "Server >> Connection: Upgrade\r\n"
    + "Server >> Upgrade: websocket\r\n"
    + "Sec-WebSocket-Accept: " + Convert.ToBase64String(
        SHA1.Create().ComputeHash(
            Encoding.UTF8.GetBytes(
                new Regex("Sec-WebSocket-Key: (.*)").Match(headerBlock).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
            )
        )
    )
    + "\r\nServer >>\r\n");
    sWriter.WriteLine(headerResponse);
}
catch (Exception)
{
    bClientConnected = false;
    client.Close();
}

// to write something back.
while (bClientConnected)
{
    try
    {
        sData = sReader.ReadLine();
        Console.WriteLine("Client >> " + sData);
        sWriter.WriteLine("");
        sWriter.Flush();
    }
    catch (Exception)
    {
        bClientConnected = false;
        client.Close();
        continue;
    }
}

Server output:

Connection Establised to: 127.0.0.1
Client << GET / HTTP/1.1
Client << Host: 127.0.0.1:8080
Client << Connection: Upgrade
Client << Pragma: no-cache
Client << Cache-Control: no-cache
Client << Upgrade: websocket
Client << Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
Client << Sec-WebSocket-Version: 13
Client << User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
Client << Accept-Encoding: gzip, deflate, sdch, br
Client << Accept-Language: en,nl;q=0.8,en-GB;q=0.6
Client << Sec-WebSocket-Key: tThSdzoXlh+jFiILH5pXSw==
Client << Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Client <<
Server >> HTTP/1.1 101 Switching Protocols
Server >> Connection: Upgrade
Server >> Upgrade: websocket
Server >> Sec-WebSocket-Accept: DBANtxNFhA+xdRW4JFvwP1HwpHA=
Server >>

So my server is responding correctly and the client is not sending anything else to me i can't work out why it wont give me the console to send raw messages to my server.

So this was an annoyingly simple problem that caused so much trouble,

I was missing sWriter.Flush(); after writing my headers.

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