我成功地在C#中創建了一個可以連接到的WebSocket服務器。我作爲RFC 6455要求的握手。無論我發送了什麼(通過WebSocket.send()
)(例如「asd」),該流只有9個字節的數據,UTF8「不可表示」。服務器沒有得到客戶端的消息
using System.Net.Sockets;
using System.Net;
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
class Server
{
public static void Main()
{
TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
server.Start();
TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();
Boolean isHandshaked = false;
while (true)
{
while (!stream.DataAvailable)
{
}
Byte[] bytes = new Byte[client.Available];
stream.Read(bytes, 0, bytes.Length);
if (!isHandshaked)
{
Byte[] response = Encoding.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(
Encoding.UTF8.GetString(bytes)
).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
)
)
) + Environment.NewLine
+ Environment.NewLine);
stream.Write(response, 0, response.Length);
isHandshaked = true;
}
else
{
Console.WriteLine(Encoding.UTF8.GetString(bytes));
}
}
}
}
我錯過了什麼?
我找到了算法,但我不知道如何使用它。你能舉一個例子嗎? – 2013-02-09 13:10:43
我想你是指揭露消息的算法?我已經用這個 – simonc 2013-02-09 13:22:03
的一個小例子更新了我的答案現在很清楚如何在C#中進行XOR,但是如何確定'bytes'中的掩碼和消息的位置? – 2013-02-09 14:34:10