问题描述
我在TIdTCPServer的OnExecute(安装过程中随附的Delphi 2009和Indy 10)中具有以下代码,该代码与该站点上的其他示例非常相似;
I have the following code in the OnExecute of a TIdTCPServer (Delphi 2009 and Indy 10 that came with the installation) which is very similar to other examples on this site;
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)上失败。
It doesn't read the data in sometimes as CheckForDataOnSource(10) returns False. However if I stop the debugger at that line I can see the data I sent in the InputBuffer's bytes. Are there any other setup things I should do or other ways to force this to work all the time. This code is run bunch of times but always fails on the CheckForDataOnSource(10).
另外,我注意到在Indy的代码中,有些地方抓住AContext.Connection.IOHandler而不是AContext.Connection.Socket并执行与上面的代码相同的操作,使用的是正确的代码。
Also as a side note, I notice in code for Indy around the place that some people grab the AContext.Connection.IOHandler instead of the AContext.Connection.Socket and do the same things as the code above, what is the "right" one to use.
谢谢
Bruce
推荐答案
代码应该更像这样:
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;
这篇关于TIdTCPServer有时无法从套接字读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!