Delphi Indy TIdTCPClient接收文本
我尝试在idtcpclient中接收文本,但它不起作用。这是我在计时器中使用的代码:Delphi Indy TIdTCPClient接收文本,delphi,timer,tcpclient,indy,Delphi,Timer,Tcpclient,Indy,我尝试在idtcpclient中接收文本,但它不起作用。这是我在计时器中使用的代码: procedure TForm1.Timer2Timer(Sender: TObject); var receivedtext:string; begin if idtcpclient1.Connected = true then begin with idtcpclient1 do begin if not IOHandler.InputBufferIsEmpty th
procedure TForm1.Timer2Timer(Sender: TObject);
var
receivedtext:string;
begin
if idtcpclient1.Connected = true then
begin
with idtcpclient1 do
begin
if not IOHandler.InputBufferIsEmpty then
begin
try
receivedtext := IOHandler.ReadLn;
finally
if receivedtext = '' = false then
begin
showmessage(receivedtext);
idtcpclient1.IOHandler.InputBuffer.Clear;
receivedtext := '';
end;
end;
end;
end;
end
else
begin
timer2.Enabled := false;
end;
end;
计时器的间隔为8毫秒。
定时器在连接时自动启用。
但是当我发送东西时,我没有收到消息框或错误。
我确信是我写的数据,因为当我使用tclientsocket时,我确实收到了它
我做错了什么?改用类似的方式:
procedure TForm1.Timer2Timer(Sender: TObject);
var
receivedtext: string;
begin
with IdTCPClient1 do
begin
try
if IOHandler.InputBufferIsEmpty then
begin
IOHandler.CheckForDataOnSource(0);
IOHandler.CheckForDisconnect;
if IOHandler.InputBufferIsEmpty then Exit;
end;
receivedtext := IOHandler.ReadLn;
except
Timer2.Enabled := False;
Exit;
end;
if receivedtext <> '' then
ShowMessage(receivedtext);
end;
end;
2-修改您的连接代码:
IdTCPClient1.Connect;
try
Thread := TReadingThread.Create(IdTCPClient1);
Thread.OnData := DataReceived;
Thread.Resume;
except
IdTCPClient1.Disconnect;
raise;
end;
...
if Assigned(Thread) then Thread.Terminate;
try
IdTCPClient1.Disconnect;
finally
if Assigned(Thread) then
begin
Thread.WaitFor;
FreeAndNil(Thread);
end;
end;
...
procedure TForm1.DataReceived(const Data: string);
begin
ShowMessage(Data);
end;
receivedtext==false是否编译?请显示真实代码为什么要清除InputBuffer?在一次成功的阅读之后。。。操作时,Indy将从InputBuffer中删除读取的字节。为什么计时器中有此代码?使用如图所示的代码,您将遇到重入问题,特别是计时器值为8ms时。我认为您的代码是完全错误的。使用谷歌搜索示例,如。。。这里的第一个演示应该有助于1_简单字符串交换示例
IdTCPClient1.Connect;
try
Thread := TReadingThread.Create(IdTCPClient1);
Thread.OnData := DataReceived;
Thread.Resume;
except
IdTCPClient1.Disconnect;
raise;
end;
...
if Assigned(Thread) then Thread.Terminate;
try
IdTCPClient1.Disconnect;
finally
if Assigned(Thread) then
begin
Thread.WaitFor;
FreeAndNil(Thread);
end;
end;
...
procedure TForm1.DataReceived(const Data: string);
begin
ShowMessage(Data);
end;