我正在尝试实现一个简单的Web套接字服务器和客户端。这是我第一次查看它们,很抱歉,如果这个问题很明显。
我使用的是Chrome v15,我相信它使用的是09(版本8)协议?
我只是似乎无法使他们连接。我从浏览器收到的请求是:
GET /chat HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: localhost:8181
Sec-WebSocket-Origin: http://localhost:51990
Sec-WebSocket-Key: JFAw5PLk45TodN2ERD1ePA==
Sec-WebSocket-Version: 8
Cookie: size=4; CP.mode=B; ASP.NET_SessionId=zzx3d3ajepwwycqjaj1nyex4; .ASPXAUTH=781D3791DC2483756B3DA9FA8E031A9BACD357EBD8FA23B7BCB8BDA6526F28F77FC798A0D4BEC4E2B166700B5C08FA60CBF588D292BFC1D050C9B034522C93ACBEF28BC6D51FDC5B40F6050F03758DA1A3E4D3F7484BC4F7DA3602A5FAFD3023C8D4D5929B69F88DB417CA6F366A83F334807818E2C07E23C0D0993F25B3C9BDE02A; name=Test
我注意到
Sec-WebSocket-Protocol
标头丢失了。我发送的响应如下所示:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: VAuGgaNDB/reVQpGfDF8KXeZx5o=
Sec-WebSocket-Protocol: chat
谁能告诉我我在做什么错?
编辑:我用来生成接受密钥的代码是:
public static String ComputeWebSocketHandshakeSecurityHash09(String secWebSocketKey)
{
const String MagicKEY = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
String secWebSocketAccept = String.Empty;
// 1. Combine the request Sec-WebSocket-Key with magic key.
String ret = secWebSocketKey + MagicKEY;
// 2. Compute the SHA1 hash
SHA1 sha = new SHA1CryptoServiceProvider();
byte[] sha1Hash = sha.ComputeHash(Encoding.UTF8.GetBytes(ret));
// 3. Base64 encode the hash
secWebSocketAccept = Convert.ToBase64String(sha1Hash);
return secWebSocketAccept;
}
编辑:这是响应代码:
StringBuilder mResponse = new StringBuilder();
mResponse.Append("HTTP/1.1 101 Switching Protocols" + Environment.NewLine);
mResponse.Append("Upgrade: WebSocket" + Environment.NewLine);
mResponse.Append("Connection: Upgrade" + Environment.NewLine);
mResponse.Append(String.Format("Sec-WebSocket-Accept: {0}", ComputeWebSocketHandshakeSecurityHash09(secKey)) + Environment.NewLine);
// Build the response for the client
byte[] HandshakeText = Encoding.UTF8.GetBytes(mResponse.ToString());
logger.Log("");
logger.Log("Sending handshake ...");
ConnectionSocket.BeginSend(HandshakeText, 0, HandshakeText.Length, 0, HandshakeFinished, null);
最佳答案
我设法建立连接,但发送邮件时无法解码。看看this question.
关于c# - 客户端-服务器WebSocket握手,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8093078/