C#构建Web套接字服务器

时间:2017-02-01 03:46:56

标签: c# websocket

我正在尝试使用C#构建一个WebSocket服务器,我一直在阅读教程左侧和中间位置以尝试使其正常工作。

所以我在谷歌浏览器中使用Advanced Rest Client (ARC)

建立与我的服务器的连接,但它似乎挂在“连接到远程服务器”。

我升级到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;
    }
}

服务器输出:

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

所以我的服务器响应正常,客户端没有向我发送任何其他内容我无法解决为什么它不会给我控制台将原始消息发送到我的服务器。

1 个答案:

答案 0 :(得分:0)

所以这是一个令人烦恼的简单问题,造成了很多麻烦,

写完标题后,我遗失了sWriter.Flush();