WebSocket 连接到 TIdHTTPServer,握手问题

2024-04-14

我正在使用 C++Builder 10.1 Berlin 编写一个简单的 WebSocket 服务器应用程序,该应用程序在端口上侦听从 Web 浏览器(例如 Google Chrome)发送的一些命令。

在我的表单上,我有一个 TMemo、TButton 和 TIdHTTPServer,并且我有以下代码:

void __fastcall TForm1::Button1Click(TObject *Sender)
{
 IdHTTPServer1->Bindings->DefaultPort = 55555;
 IdHTTPServer1->Active = true;
}

void __fastcall TForm1::IdHTTPServer1Connect(TIdContext *AContext)
{

  Memo1->Lines->Add(AContext->Binding->PeerIP);
  Memo1->Lines->Add( AContext->Connection->IOHandler->ReadLn(enUTF8));
  Memo1->Lines->Add( AContext->Data->ToString());

}


void __fastcall TForm5::IdHTTPServer1CommandOther(TIdContext *AContext, TIdHTTPRequestInfo *ARequestInfo,
          TIdHTTPResponseInfo *AResponseInfo)
{

UnicodeString svk,sValue;
TIdHashSHA1 *FHash;
TMemoryStream *strmRequest;

FHash = new TIdHashSHA1;
strmRequest  =  new TMemoryStream;

strmRequest->Position = 0;
svk = ARequestInfo->RawHeaders->Values["Sec-WebSocket-Key"];

Memo1->Lines->Add("Get:"+svk);
      AResponseInfo->ResponseNo         = 101;
      AResponseInfo->ResponseText       = "Switching Protocols";
      AResponseInfo->CloseConnection    = False;
      //Connection: Upgrade
      AResponseInfo->Connection         = "Upgrade";
      //Upgrade: websocket
      AResponseInfo->CustomHeaders->Values["Upgrade"] = "websocket";

      sValue = svk + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
      sValue = TIdEncoderMIME::EncodeBytes( FHash->HashString(sValue) );
      AResponseInfo->CustomHeaders->Values["Sec-WebSocket-Accept"] = sValue;
      AResponseInfo->ContentText = "Welcome here!";

      AResponseInfo->WriteHeader();

 UnicodeString URLstr = "http://"+ARequestInfo->Host+ARequestInfo->Document;
      if (ARequestInfo->UnparsedParams != "") URLstr = URLstr+"?"+ARequestInfo->UnparsedParams;
      Memo1->Lines->Add(URLstr);
      Memo1->Lines->Add(ARequestInfo->Command );
      Memo1->Lines->Add("--------");
      Memo1->Lines->Add(ARequestInfo->RawHeaders->Text );
      Memo1->Lines->Add(AContext->Data->ToString() );
}

在 Chrome 中,我执行以下 Javascript 代码:

var connection = new WebSocket('ws://localhost:55555');

connection.onopen = function () {
  connection.send('Ping');
};

但我从 Chrome 中收到此错误:

VM77:1 WebSocket 与“ws://localhost:55555/”的连接失败:一个或多个保留位打开:reserved1 = 1、reserved2 = 0、reserved3 = 0

我希望 WebSocket 连接成功,然后我可以在 Web 浏览器和服务器应用程序之间发送数据。

也许有人已经知道出了什么问题,并且可以展示如何实现这一目标的完整示例?


这是我的应用程序的 Memo1 显示的内容:



192.168.0.25
GET / HTTP/1.1
Get:TnBN9qjOJiwka2eJe7mR0A==
http://
HOST:
--------
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: http://bcbjournal.org
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Sec-WebSocket-Key: TnBN9qjOJiwka2eJe7mR0A==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
  

Chrome 浏览器显示的内容如下:

响应请求:



HTTP/1.1 101 Switching Protocols
Connection: Upgrade
Content-Type: text/html; charset=ISO-8859-1
Content-Length: 13
Date: Thu, 08 Jun 2017 15:04:00 GMT
Upgrade: websocket
Sec-WebSocket-Accept: 2coLmtu++HmyY8PRTNuaR320KPE=
  

请求标头



GET ws://192.168.0.25:55555/ HTTP/1.1
Host: 192.168.0.25:55555
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: http://bcbjournal.org
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Sec-WebSocket-Key: TnBN9qjOJiwka2eJe7mR0A==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
  

你滥用了TIdHTTPServer

你犯了两个大错误:

  1. Your OnConnect事件处理程序正在读取客户端的初始 HTTP 请求行(GET线)。它根本不应该从客户端读取任何内容,因为这样做会干扰TIdHTTPServerHTTP 协议的处理。

    事件处理程序读取请求行并退出后,TIdHTTPServer然后读取下一行(Hostheader)并将其解释为请求行,这就是原因:

    • the ARequestInfo->Command财产是"HOST:"代替"GET".

    • the ARequestInfo->Host, ARequestInfo->Document, ARequestInfo->Version, ARequestInfo->VersionMajor, ARequestInfo->VersionMinor属性全错了。

    • 你最终不得不使用OnCommandOther当你应该使用的事件OnCommandGet事件代替。

  2. 您正在访问TMemo在你的TIdHTTPServer事件不与主 UI 线程同步。TIdHTTPServer是一个多线程组件。它的事件在工作线程的上下文中触发。 VCL/FMX UI 控件不是线程安全的,因此您必须与主 UI 线程正确同步。

您没有正确实现 WebSocket 协议

您的服务器并未验证 WebSocket 协议要求服务器验证的握手中的所有内容(这对于测试来说很好,但请确保在生产中这样做)。

但更重要的是,TIdHTTPServer不太适合实现 WebSockets(即待办事项 https://github.com/IndySockets/Indy/issues/85)。 WebSocket 协议唯一涉及 HTTP 的就是握手。握手完成后,其他的都是WebSocket帧,而不是HTTP。为了处理这个问题TIdHTTPServer要求您实施entireWebSocket 会话内部OnCommandGet事件,读取并发送所有 WebSocket 帧,防止事件处理程序退出,直到连接关闭。对于这种逻辑,我建议使用TIdTCPServer直接代替,只需在其开始时手动处理 HTTP 握手OnExecute事件,然后循环处理 WebSocket 帧的其余事件。

Your OnCommandOther握手完成后,事件处理程序当前不执行任何 WebSocket I/O。它正在将控制权归还给TIdHTTPServer,然后它将尝试读取新的 HTTP 请求。一旦客户端向服务器发送 WebSocket 帧,TIdHTTPServer由于它不是 HTTP,因此将无法处理它,并且可能会将 HTTP 响应发送回客户端,这将被误解,导致客户端 WebSocket 会话失败并关闭套接字连接。


话虽如此,尝试更像这样的事情:

#include ...
#include <IdSync.hpp>

class TLogNotify : public TIdNotify
{
protected:
    String FMsg;

    void __fastcall DoNotify()
    {
        Form1->Memo1->Lines->Add(FMsg);
    }

public:
    __fastcall TLogNotify(const String &S) : TIdNotify(), FMsg(S) {}
};

__fastcall TForm1::TForm1(TComponent *Owner)
    : TForm(Owner)
{
    IdHTTPServer1->DefaultPort = 55555;
}

void __fastcall TForm1::Log(const String &S)
{
    (new TLogNotify(S))->Notify();
}

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    IdHTTPServer1->Active = true;
}

void __fastcall TForm1::IdHTTPServer1Connect(TIdContext *AContext)
{
    Log(_D("Connected: ") + AContext->Binding->PeerIP);
}

void __fastcall TForm1::IdHTTPServer1Disconnect(TIdContext *AContext)
{
    Log(_D("Disconnected: ") + AContext->Binding->PeerIP);
}

void __fastcall TForm5::IdHTTPServer1CommandGet(TIdContext *AContext, TIdHTTPRequestInfo *ARequestInfo, TIdHTTPResponseInfo *AResponseInfo)
{
    Log(ARequestInfo->RawHTTPCommand);

    if (ARequestInfo->Document != _D("/"))
    {
        AResponseInfo->ResponseNo = 404;
        return;
    }

    if ( !(ARequestInfo->IsVersionAtLeast(1, 1) &&
          TextIsSame(ARequestInfo->RawHeaders->Values[_D("Upgrade")], _D("websocket")) &&
          TextIsSame(ARequestInfo->Connection, _D("Upgrade")) ) )
    {
        AResponseInfo->ResponseNo         = 426;
        AResponseInfo->ResponseText       = _D("upgrade required");
        return;
    }

    String svk = ARequestInfo->RawHeaders->Values[_D("Sec-WebSocket-Key")];

    if ( (ARequestInfo->RawHeaders->Values[_D("Sec-WebSocket-Version")] != _D("13")) ||
          svk.IsEmpty() )
    {
        AResponseInfo->ResponseNo = 400;
        return;
    }

    // validate Origin, Sec-WebSocket-Protocol, and Sec-WebSocket-Extensions as needed...

    Log(_D("Get:") + svk);

    AResponseInfo->ResponseNo         = 101;
    AResponseInfo->ResponseText       = _D("Switching Protocols");
    AResponseInfo->CloseConnection    = false;
    AResponseInfo->Connection         = _D("Upgrade");
    AResponseInfo->CustomHeaders->Values[_D("Upgrade")] = _D("websocket");

    TIdHashSHA1 *FHash = new TIdHashSHA1;
    try {
        String sValue = svk + _D("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
        sValue = TIdEncoderMIME::EncodeBytes( FHash->HashString(sValue) );
        AResponseInfo->CustomHeaders->Values[_D("Sec-WebSocket-Accept")] = sValue;
    }
    __finally {
        delete FHash;
    }

    AResponseInfo->WriteHeader();

    String URLstr = _D("http://") + ARequestInfo->Host + ARequestInfo->Document;
    if (!ARequestInfo->UnparsedParams.IsEmpty()) URLstr = URLstr + _D("?") + ARequestInfo->UnparsedParams;
    Log(URLstr);
    Log(_D("--------"));
    Log(ARequestInfo->RawHeaders->Text);

    // now send/receive WebSocket frames here as needed,
    // using AContext->Connection->IOHandler directly...
}

话虽这么说,有很多可用的第 3 方 WebSocket 库。您应该使用其中之一,而不是手动实现 WebSocket。有些库甚至构建在 Indy 之上。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

WebSocket 连接到 TIdHTTPServer,握手问题 的相关文章