简体   繁体   English

用C#编写WebSocket服务器

[英]Write a WebSocket server in C#

I write code like in this article . 我像本文一样编写代码。 My code: 我的代码:

static void Main()
{
    TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 8080);
    server.Start();

    Console.WriteLine("Server has started on 127.0.0.1:8080");
    Console.WriteLine("Waiting for a connection...");

    TcpClient client = server.AcceptTcpClient();

    Console.Write("A client connected.");

    NetworkStream stream = client.GetStream();

    //enter to an infinite cycle to be able to handle every change in stream
    while (true)
    {
        while (!stream.DataAvailable) ;

        byte[] bytes = new byte[client.Available];
        stream.Read(bytes, 0, bytes.Length);

        //translate bytes of request to string
        string request = Encoding.UTF8.GetString(bytes);
        if (new Regex("^GET").IsMatch(request))
        {
            byte[] response = UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine
                + "Connection: Upgrade" + Environment.NewLine
                + "Upgrade: websocket" + Environment.NewLine
                + "Sec-WebSocket-Accept: " + Convert.ToBase64String(
                    SHA1.Create().ComputeHash(
                        Encoding.UTF8.GetBytes(
                            new Regex("Sec-WebSocket-Key: (.*)").Match(request).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
                        )
                    )
                ) + Environment.NewLine + Environment.NewLine);

            stream.Write(response, 0, response.Length);
        }
        else
        {
            byte[] response = UTF8.GetBytes("Data received");
            response[0] = 0x81; // denotes this is the final message and it is in text
            response[1] = (byte)(response.Length - 2); // payload size = message - header size
            stream.Write(response, 0, response.Length);
        }
    }
}

I try debug to see it work, but it runs to the line 我尝试调试以查看它是否有效,但它会运行到该行

TcpClient client = server.AcceptTcpClient();

and stops. 并停止。 It shows Waiting for a connection... and stops. 它显示Waiting for a connection...并停止。

As #Blorgbeard mentioned should have client as well, you can check this code https://github.com/sta/websocket-sharp 由于#Blorgbeard提到也应该有客户端,你可以检查这段代码https://github.com/sta/websocket-sharp

Or Simple code like this: 或者像这样的简单代码:

var tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");

tcpclnt.Connect(IPAddress.Parse("127.0.0.1"), 8080);
// use the ipaddress as in the server program

Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");

String str = Console.ReadLine();
Stream stm = tcpclnt.GetStream();

ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
Console.WriteLine("Transmitting.....");

stm.Write(ba, 0, ba.Length);

byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);

for (int i = 0; i < k; i++)
   Console.Write(Convert.ToChar(bb[i]));

tcpclnt.Close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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