我写的代码类似于这篇文章中的示例。我的代码:
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