Delphi Indy相当于Python的Socket.recv?

时间:2013-01-10 17:52:53

标签: delphi indy recv

我在Python中使用了这段代码:

s = socket.create_connection(('192.168.0.111', 123), timeout=2.0)
s.sendall('REQUEST,status,interface'); result = s.recv(1024)

如何使用Indy组件中的TIdTCPClient在Delphi中执行“s.recv(1024)”?服务器返回一个没有任何终止符的字符串,因此ReadLn不起作用。

1 个答案:

答案 0 :(得分:4)

在Python中,recv(1024)只读取套接字上可用的内容,最多1024个字节。可以使用TIdTCPClient(见下文)执行相同的操作,但它通常不是处理套接字编程的最佳方法。您真的需要知道服务器实际上是如何终止数据的。它在发送数据后是否关闭了连接的末尾?如果没有,它是否期望您只需读取任何可用的字节,无论实际长度如何?如果是这样,它如何期望您处理TCP数据包碎片(TCP / IP可以将传输的数据分成多个数据包,并且可能会以多个数据包的形式接收数据,即使它们不是这样发送的)?是否希望您在发生超时之前继续阅读,表示没有更多数据被发送?

在编写代码以正确处理读取方面,这会产生很大的不同。例如:

IdTCPClient1.Host := '192.168.0.111';
IdTCPClient1.Port := 123;
IdTCPClient1.ConnectTimeout := 2000;
IdTCPClient1.Connect;
try
  IdTCPClient1.IOHandler.Write('REQUEST, status, interface');

  // wait for a disconnect then return everything that was received
  Result := IdTCPClient1.IOHandler.AllData;
finally
  IdTCPClient1.Disconnect;
end;

Vs的:

IdTCPClient1.Host := '192.168.0.111';
IdTCPClient1.Port := 123;
IdTCPClient1.ConnectTimeout := 2000;
IdTCPClient1.Connect;
try
  IdTCPClient1.IOHandler.Write('REQUEST, status, interface');

  // set the max number of bytes to read at one time
  IdTCPClient1.IOHandler.RecvBufferSize := 1024;

  // read whatever is currently in the socket's receive buffer, up to RecvBufferSize number of bytes
  IdTCPClient1.IOHandler.CheckForDataOnSource;

  // return whatever was actually read
  Result := IdTCPClient1.IOHandler.InputBufferAsString;
finally
  IdTCPClient1.Disconnect;
end;

Vs的:

IdTCPClient1.Host := '192.168.0.111';
IdTCPClient1.Port := 123;
IdTCPClient1.ConnectTimeout := 2000;
IdTCPClient1.Connect;
try
  IdTCPClient1.IOHandler.Write('REQUEST, status, interface');

  // keep reading until 5s of idleness elapses
  repeat until not IdTCPClient1.IOHandler.CheckForDataOnSource(5000);

  // return whatever was actually read
  Result := IdTCPClient1.IOHandler.InputBufferAsString;
finally
  IdTCPClient1.Disconnect;
end;