用C#编写WebSocket服务器

3

我写的代码类似于这篇文章中的示例。我的代码:

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);
        }
    }
}

我尝试调试以查看它是否工作,但它运行到了该行。

TcpClient client = server.AcceptTcpClient();

程序停止运行,并显示 等待连接...


你试过连接它了吗?AcceptTcpClient会阻塞线程,直到有实际连接。尝试在你的浏览器中导航到http://localhost:8281 - Blorgbeard
哇!我尝试了一下,它起作用了。非常感谢你。#Blorgbeard,我想发送一个字符串:“Hello world”,你能帮我吗? - Ta No Bi
看起来你对C#的经验不是很丰富。我建议你从比这更简单的任务开始。然后几个月后再回来。 - abatishchev
1个回答

3
如#Blorgbeard所述,应该有客户端,你可以查看这段代码https://github.com/sta/websocket-sharp

或者像这样的简单代码:

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();

Peyman 我尝试运行代码,但出现了以下错误:http://i.imgur.com/0AXL6vD.png

- Ta No Bi
你创建了控制台应用程序项目吗? - Peyman
#Peyman 我运行了这段代码:https://github.com/sta/websocket-sharp。它显示以下错误。 我按照 "或者像这样的简单代码:" 运行了代码,它在以下行显示错误: tcpclnt.Connect(IPAddress); 错误信息为:"System.Net.IPAddress" 是一种类型,但被用作 '变量'。如果我删除 tcpclnt.Connect(IPAddress),它会显示错误:"System.InvalidOperationException" 类型的未处理异常发生在 System.dll 中。额外信息:对于未连接的套接字,不允许进行该操作。在 Stream stm = tcpclnt.GetStream() 的行中。 - Ta No Bi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接