3

I've been trying to set the length of the amount of characters you recover from the ReceiveText TClientSocket function and nothing seems to be working. E.g., Receiving the first leftmost character(s) from the recovered data or otherwise data stream. Is there a way to accomplish this in Delphi using this specific object?

Help would be much appreciated. Thanks in advance.

4

3 回答 3

1

ReceiveText没有任何方法来控制接收到的文本的最大长度。

模式中最简单的方法ClientType := ctBlocking是使用 aTWinSocketStream作为文档所述:

http://docwiki.embarcadero.com/VCL/XE2/en/ScktComp.TClientSocket.ClientType

ClientType 为 ctBlocking 时,使用 TWinSocketStream 对象进行读写。如果在读取或写入时出现问题,TWinSocketStream 可防止应用程序无限期挂起。它还可以等待套接字连接表明它已准备好读取。

示例代码:

var
  Stream : TWinSocketStream;
  Buffer : TBytes;
  S      : string;
begin
  SetLength(Buffer, 100); // 100 bytes buffer size
  Stream := TWinSocketStream.Create(Socket, 5000); // 5 seconds or 5000 milliseconds
  try
    Stream.ReadBuffer(Buffer[0], Length(Buffer)); // raises an Exception if it couldn't read the number of bytes requested
    S := TEncoding.Default.GetString(Buffer); // Works in Delphi 2009+
  finally
    Stream.Free;
  end;
end;
于 2012-02-08T17:42:35.653 回答
1

这是发送和接收文本的小技巧

首先,您也必须发送文本的长度

Socket.SendText(IntToStr(Length(text)) + seperator + text);

然后你可以检查你的服务器套接字接收数据流,如果你的传入文本是完整的

procedure TMyServer.OnClientRead(Sender: TObject; Socket: TCustomWinSocket);
begin
  if (xRecLength = 0) then begin
    if Length(Socket.ReceiveText) <= 0 then EXIT;
    xRecLength:= StrToIntDef(GetFirstFromSplitted(Socket.ReceiveText, seperator), -1);
    if xRecLength = -1 then EXIT;
  end;
  xActLength:= xActLength + Length(Socket.ReceiveText);
  xRecPuffer:= xRecPuffer + Socket.ReceiveText;

  isComplete:= xActLength = xRecLength;
  if isComplete then begin
    // complete text received
  end;
end;

希望对你有帮助...

于 2012-02-08T07:58:03.470 回答
0

我不熟悉 Delphi,但快速谷歌搜索出现了这个页面,表明它ReceiveText不接受任何参数,而是返回一个它可以读取的字符串。

您可能需要的是ReceiveBuf代替。

于 2012-02-08T07:10:22.270 回答