读取TidTCPServer传入数据直到断开连接

时间:2019-05-22 16:10:08

标签: indy10

我正在尝试从Delphi的TTCPserver迁移到Indy的TidTCPServer(Delphi XE10.2),但是我无法弄清楚如何在Execute中读取传入的数据,我发现的所有示例都是使用readln,它需要一个“ ETX ” char。而且我还没有找到接收到的任何字节或任何长度的消息。

那我如何阅读完整的包裹? 我想象过类似的事情; 读取字节,直到“断开连接”

我在下面尝试了此操作(虽然不是在同一时间),但是除了使用telnet客户端并从键盘上键入字符的情况下,我没有得到任何包或字节。这将逐字节提供数据。但是,“ 3rd party client”的软件包永远不会出现。我看到客户端再次连接并断开连接。

procedure TForm2.IdTCPServerExecute(AContext: TIdContext);
var
    Port          : Integer;
    PeerPort      : Integer;
    PeerIP        : string;
    msgFromClient : string;
    msgToClient   : string;
    buf : TidBytes;
    l :integer;
    ABufStream : TMemoryStream;
begin
// this doesn't return anything
    ABufStream := TMemoryStream.Create;
    try
     //       AContext.Connection.IOHandler.ReadStream(ABufStream, -1, True);
      AContext.Connection.IOHandler.InputBufferToStream(ABufStream, -1);
      ABufStream.Position := 0;
      ABufStream.WriteBuffer(buf, ABufStream.Size);
      msgFromClient := format('received %d bytes',[ABufStream.Size]);
    finally
       ABufStream.Free;
    end;

// this doesn't return anything neither
    AContext.Connection.IOHandler.ReadBytes(buf, -1, False);
    l := length(buf);
    if l > 0 then
      Display('CLIENT', '(Bytes =' + IntToStr(l));
end;

我收到的数据是一个“字节数组”,其中没有ETX(或包结尾),其工作方式如下

  1. 客户端连接(启动tcp会话)
  2. 客户端发送N字节的数据包
  3. 客户端断开连接(TCP会话结束)

该程序包在头8个字节中包含标题和数据部分的长度。

我来自TTCPServer的旧代码如下:

procedure TDispatchScanThread.TCPServerOnAccept(Sender: TObject; ClientSocket: TCustomIpClient);
var
  s: ShortString;
  l: integer;
  Buf: TDataBuf; // TDataBuf = array[0..MAX_DATAPACKET] of byte;
  ADispatchPacket: TDispatchPacket;
  AQueuedStatus : Boolean;

begin
  try
    LogQueue.AddToLog(format('TCPServer receiving (onAccept)',[]), llvVerbose);
    ZeroMemory(@Buf, MAX_DATAPACKET);
    l := ClientSocket.PeekBuf(Buf, 8);
    if (l <> SOCKET_ERROR) and (l = 8) then
    begin
      s := '0000';       // check if IVD version header is valid for us
      Move(Buf[0], s[1], 4);
      if not(s = sHeaderID) then
        raise Exception.CreateFmt('Invalid dispatch packet HeaderID %s', [s]);

      s := '0000';       // Fetch data package length
      Move(Buf[4], s[1], 4);
      l := StrToInt(s);
      ClientSocket.ReceiveBuf(Buf[0], l + HEADER_SIZE);       // total length is header + data

      // Create the dispatch packet object, move the data to the buffer and queue it.
      ADispatchPacket := TDispatchPacket.Create;
      ADispatchPacket.ReplyTime := MilliSecondOfTheDay(UTCNow);
      ADispatchPacket.DataBuf := Buf; // the setter copies the buffer contens

      AQueuedStatus := CommandQueue.Enqueue(TOmniMessage.Create(ord(itmDispatchPackage), ADispatchPacket));
      LogQueue.AddToLog(Format('Received package: %d bytes, incomming package was queued = [%s]',[l + HEADER_SIZE, booltostr(AQueuedStatus, True)]), llvVerbose);
    end else
        begin
          LogQueue.AddError(format('TCPServer socket error: %d',[l]));
        end;
  except
    on E: Exception do
    begin
      LogQueue.AddError(format('TcpServerAccept Error: %s',[E.Message]));
      FreeAndNil(ADispatchPacket);
    end;
  end; // except
end;

1 个答案:

答案 0 :(得分:1)

您收到的消息具有一个结构-一个4字节的消息ID,后跟一个4字节的ASCII字符串,指定消息数据的长度,然后是实际的消息数据。

您的TTCPServer代码遵循该结构,但您的TIdTCPServer代码却没有(甚至没有结束!)。如果有的话,Indy使这种工作变得容易,因为Indy的TIdIOHandler类具有许多可用于读取各种数据格式的方法,而TTCPServer并没有提供任何帮助您的方法,因此您必须手动读取和解析所有内容。

在这种情况下,您可以使用TIdIOHandler.ReadString()TIdIOHandler.ReadBytes()方法,例如:

procedure TForm2.IdTCPServerExecute(AContext: TIdContext);
var
  s: string;
  l: integer;
  Buf: TDataBuf; // TDataBuf = array[0..MAX_DATAPACKET] of byte;
  ADispatchPacket: TDispatchPacket;
  AQueuedStatus : Boolean;
  IdBuf: TIdBytes;
begin
  LogQueue.AddToLog(format('TCPServer receiving (onExecute)',[]), llvVerbose);
  ZeroMemory(@Buf, MAX_DATAPACKET);

  // check if IVD version header is valid for us
  s := AContext.Connection.IOHandler.ReadString(4);
  if s <> sHeaderID then
    raise Exception.CreateFmt('Invalid dispatch packet HeaderID %s', [s]);
  Move(ShortString(s)[1], Buf[0], 4);

  s := AContext.Connection.IOHandler.ReadString(4);
  l := StrToInt(s);
  Move(ShortString(s)[1], Buf[4], 4);

  AContext.Connection.IOHandler.ReadBytes(IdBuf, l);
  Move(PByte(IdBuf)^, Buf[8], l);

  // Create the dispatch packet object, move the data to the buffer and queue it.
  ADispatchPacket := TDispatchPacket.Create;
  try
    ADispatchPacket.ReplyTime := MilliSecondOfTheDay(UTCNow);
    ADispatchPacket.DataBuf := Buf; // the setter copies the buffer contens

    AQueuedStatus := CommandQueue.Enqueue(TOmniMessage.Create(ord(itmDispatchPackage), ADispatchPacket));
  except
    ADispatchPacket.Free;
    raise;
  end;

  LogQueue.AddToLog(Format('Received package: %d bytes, incomming package was queued = [%s]',[l + HEADER_SIZE, booltostr(AQueuedStatus, True)]), llvVerbose);

  AContext.Connection.Disconnect;
end;

procedure TForm2.IdTCPServerException(AContext: TIdContext; AException: Exception);
begin
  LogQueue.AddError(format('TcpServer Error: %s',[AException.Message]));
end;

或者,您可以使用TIdIOHandler.ReadStream()方法,例如:

procedure TForm2.IdTCPServerExecute(AContext: TIdContext);
var
  s: ShortString;
  l: integer;
  Buf: TDataBuf; // TDataBuf = array[0..MAX_DATAPACKET] of byte;
  ADispatchPacket: TDispatchPacket;
  AQueuedStatus : Boolean;
  ABufStream : TIdMemoryBufferStream;
begin
  LogQueue.AddToLog(format('TCPServer receiving (onExecute)',[]), llvVerbose);
  ZeroMemory(@Buf, MAX_DATAPACKET);

  ABufStream := TIdMemoryBufferStream.Create(@Buf, SizeOf(Buf));
  try
    AContext.Connection.IOHandler.ReadStream(ABufStream, 8, False);

    // check if IVD version header is valid for us
    s := '0000';       // check if IVD version header is valid for us
    Move(Buf[0], s[1], 4);
    if s <> sHeaderID then
      raise Exception.CreateFmt('Invalid dispatch packet HeaderID %s', [s]);

    s := '0000';       // Fetch data package length
    Move(Buf[4], s[1], 4);
    l := StrToInt(s);
    AContext.Connection.IOHandler.ReadStream(ABufStream, l, False);

    // Create the dispatch packet object, move the data to the buffer and queue it.
    ADispatchPacket := TDispatchPacket.Create;
    try
      ADispatchPacket.ReplyTime := MilliSecondOfTheDay(UTCNow);
      ADispatchPacket.DataBuf := Buf; // the setter copies the buffer contens

      AQueuedStatus := CommandQueue.Enqueue(TOmniMessage.Create(ord(itmDispatchPackage), ADispatchPacket));
    except
      ADispatchPacket.Free;
      raise;
    end;
  finally
    ABufStream.Free;
  end;

  LogQueue.AddToLog(Format('Received package: %d bytes, incomming package was queued = [%s]',[l + HEADER_SIZE, booltostr(AQueuedStatus, True)]), llvVerbose);

  AContext.Connection.Disconnect;
end;

procedure TForm2.IdTCPServerException(AContext: TIdContext; AException: Exception);
begin
  LogQueue.AddError(format('TcpServer Error: %s',[AException.Message]));
end;

或者:

procedure TForm2.IdTCPServerExecute(AContext: TIdContext);
var
  s: ShortString;
  l: integer;
  Buf: TDataBuf; // TDataBuf = array[0..MAX_DATAPACKET] of byte;
  ADispatchPacket: TDispatchPacket;
  AQueuedStatus : Boolean;
  ABufStream : TIdMemoryBufferStream;
begin
  LogQueue.AddToLog(format('TCPServer receiving (onExecute)',[]), llvVerbose);
  ZeroMemory(@Buf, MAX_DATAPACKET);

  ABufStream := TIdMemoryBufferStream.Create(@Buf, SizeOf(Buf));
  try
    AContext.Connection.IOHandler.ReadStream(ABufStream, -1, True);

    if ABufStream.Size < 8 then
      raise Exception.CreateFmt('Invalid dispatch packet Header size %d', [ABufStream.Size]);

    // check if IVD version header is valid for us
    s := '0000';       // check if IVD version header is valid for us
    Move(Buf[0], s[1], 4);
    if s <> sHeaderID then
      raise Exception.CreateFmt('Invalid dispatch packet HeaderID %s', [s]);

    s := '0000';       // Fetch data package length
    Move(Buf[4], s[1], 4);
    l := StrToInt(s);

    if ABufStream.Size < (l + HEADER_SIZE) then
      raise Exception.CreateFmt('Invalid dispatch packet size %d, expected %d', [ABufStream.Size, l + HEADER_SIZE]);

    // Create the dispatch packet object, move the data to the buffer and queue it.
    ADispatchPacket := TDispatchPacket.Create;
    try
      ADispatchPacket.ReplyTime := MilliSecondOfTheDay(UTCNow);
      ADispatchPacket.DataBuf := Buf; // the setter copies the buffer contens

      AQueuedStatus := CommandQueue.Enqueue(TOmniMessage.Create(ord(itmDispatchPackage), ADispatchPacket));
    except
      ADispatchPacket.Free;
      raise;
    end;
  finally
    ABufStream.Free;
  end;

  LogQueue.AddToLog(Format('Received package: %d bytes, incomming package was queued = [%s]',[l + HEADER_SIZE, booltostr(AQueuedStatus, True)]), llvVerbose);
end;

procedure TForm2.IdTCPServerException(AContext: TIdContext; AException: Exception);
begin
  LogQueue.AddError(format('TcpServer Error: %s',[AException.Message]));
end;