Websocket server in C ++ programming error

I am trying to create a websocket server program. Here is the confirmation code. However, when I try to connect using chrome, the connection is dropped. Check it out and see if you can find any error.

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;
    }

      

For testing purposes:

key = "dGhlIHNhbXBsZSBub25jZQ =="

unique key = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"

sha1 hash: "b37a4f2cc0624f1690f64606cf385945b2bec4ea"

This is generated by my sha1 hash function.

actual sha1 hash by RFC6455 : "0xb3 0x7a 0x4f 0x2c 0xc0 0x62 0x4f 0x16 0x90 0xf6 0x46 0x06 0xcf 0x38 0x59 0x45 0xb2 0xbe 0xc4 0xea"

base64 encoded = "YjM3YTRmMmNjMDYyNGYxNjkwZjY0NjA2Y2YzODU5NDViMmJlYzRlYQ =="

This is generated by my base64 encoder

actual base64 encoding according to RFC6455 : "s3pPLMBiTxaQ9kYGzzhZRbK + xOo ="

Google chrome sends handshake data in the format:

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

      

+3


source to share


1 answer


You need to encode the byte hash values. Right now, you are converting the hash to a hexadecimal string before encoding it.

Decode "s3pPLMBiTxaQ9kYGzzhZRbK + xOo =" and convert the output to the sixth line and you will see itB3 7A 4F 2C C0 62 4F 16 90 F6 46 06 CF 38 59 45 B2 BE C4 EA



"YjM3YTRmMmNjMDYyNGYxNjkwZjY0NjA2Y2YzODU5NDViMmJlYzRlYQ ==" , on the other hand, when the decoded results (string) "b37a4f2cc0624f1690f64606cf385945b2bec4ea" .

+1


source







All Articles