[英]Delphi - Can indy TIdTCPClient Send/Receive large streams at the same time
[英]Indy TIdTCPClient receive text
我嘗試在 idtcpclient 中接收文本,但它不起作用。 這是我在計時器中使用的代碼:
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;
話雖如此,這種代碼最好使用工作線程而不是計時器來實現。
1 - 創建一個從TThread
派生的新類(文件 > 新建 > 其他 > 線程對象)
type
TDataEvent = procedure(const Data: string) of object;
TReadingThread = class(TThread)
private
FClient: TIdTCPClient;
FData: string;
FOnData: TDataEvent;
procedure DataReceived;
protected
procedure Execute; override;
public
constructor Create(AClient: TIdTCPClient); reintroduce;
property OnData: TDataEvent read FOnData write FOnData;
end;
constructor TReadingThread.Create(AClient: TIdTCPClient);
begin
inherited Create(True);
FClient := AClient;
end;
procedure TReadingThread.Execute;
begin
while not Terminated do
begin
FData := FClient.IOHandler.ReadLn;
if (FData <> '') and Assigned(FOnData) then
Synchronize(DataReceived);
end;
end;
procedure TReadingThread.DataReceived;
begin
if Assigned(FOnData) then
FOnData(FData);
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.