用 C# 编写 WebSocket 服务器
Posted
技术标签:
【中文标题】用 C# 编写 WebSocket 服务器【英文标题】:Write a WebSocket server in C# 【发布时间】:2015-03-10 03:23:54 【问题描述】:我编写类似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...
并停止。
【问题讨论】:
嗯,您尝试连接到它吗?AcceptTcpClient
阻塞线程,直到有东西真正连接。尝试在您的网络浏览器中导航到http://localhost:8281
。
哇!我试过了,它奏效了。非常感谢你。 #Blorgbeard,我想发送一个字符串:“Hello word”,你能帮帮我吗?
看来你对C#的经验并不多。我建议从比这更简单的任务开始。然后在几个月后回来。
【参考方案1】:
由于#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 我尝试运行代码。以下图片错误:i.imgur.com/0AXL6vD.png 你创建了Console Application项目吗? #Peyman 我运行代码:github.com/sta/websocket-sharp。它在下面显示错误。我按照“或这样的简单代码:”运行代码,它显示错误行:tcpclnt.Connect(IPAddress);错误:“System.Net.IPAddress”是类型,但用作“变量”。如果我删除 tcpclnt.Connect(IPAddress),它会显示错误:“System.dll 中发生‘System.InvalidOperationException’类型的未处理异常附加信息:在未连接的套接字上不允许该操作。”在行中 Stream stm = tcpclnt.GetStream()以上是关于用 C# 编写 WebSocket 服务器的主要内容,如果未能解决你的问题,请参考以下文章
使用 C# 和 AWS 证书保护 WebSocket 服务器