[英]TIdTCPServer not reading data from socket sometimes
我在TIdTCPServer的OnExecute中安装了以下代码(安装过程中随附的Delphi 2009和Indy 10),与该站点上的其他示例非常相似;
Socket := AContext.Connection.Socket;
if Socket.CheckForDataOnSource(10) then
begin
if not Socket.InputBufferIsEmpty then
begin
Socket.InputBuffer.ExtractToBytes(RawBytes, -1, False, -1);
SetLength(Buffer, Length(RawBytes));
Move(RawBytes[0], Buffer[1], Length(RawBytes));
// Do stuff with data here...
end;
end;
AContext.Connection.CheckForGracefulDisconnect;
由于CheckForDataOnSource(10)返回False,有时它不会读取数据。 但是,如果我在该行停止调试器,则可以在InputBuffer的字节中看到发送的数据。 是否还有其他应做的设置工作或其他方法可以强制其始终正常运行。 该代码运行了很多次,但始终在CheckForDataOnSource(10)上失败。
另外,我注意到在Indy的代码中,有些人抓住了AContext.Connection.IOHandler而不是AContext.Connection.Socket,并执行与上面的代码相同的操作,什么是“正确”的代码?使用。
谢谢
布鲁斯
该代码应该更像这样:
var
IO: TIdIOHandler.
Buffer: RawByteString;
begin
IO := AContext.Connection.IOHandler;
if IO.InputBufferIsEmpty then
begin
IO.CheckForDataOnSource(10);
if IO.InputBufferIsEmpty then Exit;
end;
IO.InputBuffer.ExtractToBytes(RawBytes, -1, False, -1);
// or: IO.ReadBytes(RawBytes, -1, False);
SetLength(Buffer, Length(RawBytes));
BytesToRaw(RawBytes, Buffer[1], Length(RawBytes));
// Do stuff with Buffer here...
end;
看起来您的代码应如下所示;
Socket := AContext.Connection.Socket;
Socket.CheckForDataOnSource(10);
if not Socket.InputBufferIsEmpty then
begin
Socket.InputBuffer.ExtractToBytes(RawBytes, -1, False, -1);
SetLength(Buffer, Length(RawBytes));
Move(RawBytes[0], Buffer[1], Length(RawBytes));
// Do stuff with data here...
end;
AContext.Connection.CheckForGracefulDisconnect;
抓取什么IOHandler无关紧要,因此通用类似乎很容易。
很抱歉回答我自己的问题,但对某人可能会很有益...也许。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.