gpt4 book ai didi

c# - 用 C# 编写 WebSocket 服务器

转载 作者:行者123 更新时间:2023-11-30 16:55:49 25 4
gpt4 key购买 nike

我写的代码像 in this article .我的代码:

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

然后停下来。它显示 Waiting for a connection... 并停止。

最佳答案

因为#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();

关于c# - 用 C# 编写 WebSocket 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28955639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com