Websockets using asio c++ library for the server and javascript as client

久未见 提交于 2019-12-01 22:53:16

Your's javascript code is sending header which you pointed and waiting header like:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: 5A4gqmvwM2kbopObEm+Kr6zBrNw=
Sec-WebSocket-Protocol: echo-protocol

But you send back same header that has gotten. It is not correct. So you are getting "Connection closed...". You should make header with correct value for Sec-WebSocket-Accept.

For example, do_write method may look

  void do_write(std::size_t length)
  {
    auto self(shared_from_this());

    std::stringstream handshake;

    std::string tmp(data_);
    tmp.erase(0, tmp.find("Sec-WebSocket-Key: ") + strlen("Sec-WebSocket-Key: "));
    auto key = tmp.substr(0, tmp.find("\r\n"));

    auto sha1 = SimpleWeb::Crypto::SHA1(key + ws_magic_string);

    handshake << "HTTP/1.1 101 Switching Protocols\r\n";
    handshake << "Upgrade: websocket\r\n";
    handshake << "Connection: Upgrade\r\n";
    handshake << "Sec-WebSocket-Accept: " << SimpleWeb::Crypto::Base64::encode(sha1) << "\r\n";
    handshake << "Sec-WebSocket-Protocol: echo-protocol\r\n";
    handshake << "\r\n";

    boost::asio::async_write(socket_, boost::asio::buffer(handshake.str().c_str(), handshake.str().size()),
        [this, self](boost::system::error_code ec, std::size_t /*length*/)
        {
          if (!ec)
          {
            do_read();
          }
        });
  }

Here i used Crypto's methods from project https://github.com/eidheim/Simple-WebSocket-Server, there defined ws_magic_string as

  const std::string ws_magic_string = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

Good luck.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!