如何多线程实现Ping的操作?<<<<在线等待>>>>> (200分)

  • 主题发起人 主题发起人 crazycock
  • 开始时间 开始时间
C

crazycock

Unregistered / Unconfirmed
GUEST, unregistred user!
Ping一个主机,虽然NMPing和Indy里面的idICMPClient都可以实现,
不过我觉得还是NMPing好使一些,不过让我头疼的是,如果有几十上百
个主机地址需要Ping的时候,只能1个1个Ping,而且好像在我创建的
线程里面也不能NMPing:=TNMPing.Create(Self),我该怎么做才能
实现多个线程同时Ping呢?
 
// 司马华鹏

unit PingThreadUnit;

interface

uses
Classes,IdIcmpClient,SysUtils,ComCtrls,IdStackConsts;

type
PingThread = class(TThread)
private
{ Private declarations }
protected
EchoCount:integer;
SaveTL:TListView;
PingTheIP:String;
MyIcmpClient:TIdIcmpClient;
TheMaxEchoTime:integer;
TheEchoTTl:byte;
TheEchoStr:String;
Procedure SaveIP;
Procedure PingFiveIP;
Procedure MyIdIcmpClientReply(ASender: TComponent; const AReplyStatus: TReplyStatus);
procedure Execute; override;
public
Constructor Create(TheIP:String;TheTL:TListView);
Destructor Destroy;override;
end;

implementation
uses
ScanIPUnit;

Constructor PingThread.Create(TheIP:String;TheTL:TListView);
begin
inherited Create(True);
self.FreeOnTerminate:=True;
EchoCount:=0;
PingTheIP:=TheIP;
SaveTL:=TheTL;
MyIcmpClient:=TIdIcmpClient.Create(nil);
MyIcmpClient.Protocol:=1;
MyIcmpClient.ReceiveTimeout:=5000;
MyIcmpClient.OnReply:=MyIdIcmpClientReply;
LetPingSingle.Enter;
SdPingCount:=SdPingCount+1;
LetPingSingle.Leave;
TheMaxEchoTime:=0;
TheEchoTTl:=0;
self.Suspended:=False;
end;

Procedure PingThread.SaveIP;
var
TheListItem:TListItem;
begin
try
TheListItem:=SaveTL.Items.Add;
TheListItem.ImageIndex:=0;
TheListItem.Caption:=PingTheIP;
TheLIstItem.SubItems.Add(IntToStr((EchoCount*100) div 5)+'%');
TheLIstItem.SubItems.Add(IntToStr(TheMaxEchoTime)+'''ms');
TheLIstItem.SubItems.Add(IntToStr(TheEchoTTL));
TheLIstItem.SubItems.Add(TheEchoStr);
except
end;
end;

Procedure PingThread.PingFiveIP;
var
i:integer;
begin
MyIcmpClient.Host:=PingTheIP;
for i:=1 to 5 do MyIcmpClient.Ping;
end;

procedure PingThread.Execute;
begin
try
PingFiveIP;
except
self.Terminate;
end;
end;

Procedure PingThread.MyIdIcmpClientReply(ASender: TComponent;
const AReplyStatus: TReplyStatus);
begin
Try
TheMaxEchoTime:=TheMaxEchoTime+AReplyStatus.MsRoundTripTime;
TheEchoStr:=IntToStr(AReplyStatus.BytesReceived)+'字节';
TheEchoTTl:=AReplyStatus.TimeToLive;
if (AReplyStatus.ReplyStatusType=rsEcho) then
if(AReplyStatus.FromIpAddress=PingTheIP) then
EchoCount:=EchoCount+1;
except
end;
end;

Destructor PingThread.Destroy;
begin
try
if EchoCount&gt;0 then
Synchronize(SaveIP);
except
end;
MyIcmpClient.Free;
LetPingSingle.Enter;
SdPingCount:=SdPingCount-1;
LetPingSingle.Leave;
inherited Destroy;
end;

end.
 
我去试验一下……
 
uses ScanIPUnit,在哪里啊?
 
ScanIPUnit是一个窗口,这个是一个大项目中的一段,我不能把十几万行代码都贴出来吧!
 
搞定了!!!!发分!
 
后退
顶部