建立Socket.io连接(使用DelphiWebsockets库)

时间:2018-12-24 05:01:51

标签: delphi websocket socket.io

我试图连接到Crisp服务。 我需要通过Socket.IO连接(https://docs.crisp.chat/api/v1/#header--rtm-events)订阅RTM事件

我的源代码如下:

class procedure TCrisp.InitWebSocket;
var
  TmpStrings: TStrings;
begin
  FWebSocket := TIdHTTPWebsocketClient.Create();
  FWebSocket.Host := WS_HOST; 
  FWebSocket.Port := WS_PORT;
  FWebSocket.SocketIOCompatible := True;
  FWebSocket.SocketIO.OnEvent('message:received',
    procedure(const ASocket: ISocketIOContext; const aArgument: TSuperArray; const aCallback: ISocketIOCallback)
    begin
      ShowMessage('Data PUSHED from server: ' + aArgument[0].AsJSon);
      //server wants a response?
      if aCallback <> nil then
        aCallback.SendResponse('thank for the push!');
    end);
  FWebSocket.ConnectTimeout := 15000;
  FWebSocket.Connect();
  FWebSocket.TryUpgradeToWebsocket; // <- does not work, always False
  TmpStrings := TStringList.Create();
  try
    TmpStrings.Add('{');
    TmpStrings.Add(Format('"username":"%s",', [FIdentifier]));
    TmpStrings.Add(Format('"password":"%s",', [FKey]));
    TmpStrings.Add('"routing":null,');
    TmpStrings.Add('"events":[');
    TmpStrings.Add('"message:received"');
    TmpStrings.Add('],');
    TmpStrings.Add('"rooms":["' + FWebsiteID + '"]');
    TmpStrings.Add('}');
    // Try to RTM Events subscribe
    FWebSocket.SendCmd(TmpStrings.Text); // <- Connection Closed Gracefully
//    FWebSocket.SocketIO.Send(TmpStrings.Text); // <- Cannot send: no socket.io connections!
  finally
    FreeAndNil(TmpStrings);
  end;
end;

我在做什么错?请说明正确的做法。

0 个答案:

没有答案