我正在尝试创建一个WebSocket服务器程序。这是握手代码。然而,当我使用Chrome进行连接时,连接会断开。请查看并检查是否有任何错误。
iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
if (iResult > 0)
{
char *s = strstr(recvbuf,"Sec-WebSocket-Key:");
s = s + strlen("Sec-WebSocket-Key:");
char buff[200] = {};
int i = 0;
while((int)*s != 13)
{
if((int)*s != 32)
{
buff[i] = *s;
i++;
}
s++;
}
buff[i] = '\0';
strcat(buff,"258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
hashwrapper *myWrapper = new sha1wrapper();
std::string hash(myWrapper->getHashFromString(buff));
std::string encoded = base64_encode(reinterpret_cast<const unsigned char*>(hash.c_str()), hash.length());
char * handshakeFormat = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
"Upgrade: WebSocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: %s\r\n\r\n";
memset(recvbuf,0,sizeof(recvbuf));
sprintf(recvbuf,handshakeFormat,encoded.c_str());
iSendResult = send( ClientSocket, recvbuf, iResult, 0 );
delete myWrapper;
myWrapper = NULL;
}
为了测试目的:
密钥 = "dGhlIHNhbXBsZSBub25jZQ=="
唯一密钥 = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
sha1 哈希值 : "b37a4f2cc0624f1690f64606cf385945b2bec4ea"
这是由我的 sha1 哈希函数生成的。
RFC6455 规范下的实际 sha1 哈希值: "0xb3 0x7a 0x4f 0x2c 0xc0 0x62 0x4f 0x16 0x90 0xf6 0x46 0x06 0xcf 0x38 0x59 0x45 0xb2 0xbe 0xc4 0xea"
base64 编码后 = "YjM3YTRmMmNjMDYyNGYxNjkwZjY0NjA2Y2YzODU5NDViMmJlYzRlYQ=="
这是由我的 base64 编码器生成的。
RFC6455 规范下的实际 base64 编码值: "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="
Google Chrome 以以下格式发送握手数据:
GET /?encoding=text HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: localhost:2000
Origin: http://www.websocket.org
Sec-WebSocket-Key: SEvjVT+KuQHF0TRSdop3GA==
Sec-WebSocket-Version: 13