2
我想實現一個簡單的Web套接字服務器和客戶端。這是我第一次看他們,很抱歉如果這個問題很明顯。客戶端 - 服務器WebSocket握手
我使用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);
除非我錯了,否則您的接受密鑰似乎不正確。根據輸入應該是'tixAAehY4D7GQBBUYkVMLZ3yccE ='。你怎麼計算它? (你能爲此發佈代碼嗎?) – pimvdb
好的,算出來了。在這個版本中不需要'Sec-WebSocket-Protocol:chat'。它現在連接,但只調用onclose方法clientside,而不是打開。有任何想法嗎? – RexMundi
發生這種情況時,響應在某些方面不正確。你確定添加兩個CRLF嗎? – pimvdb