我写了个简单的程序,用的是idudpClient和idudpServer,其中,发送广播并接收部分写进了一个线程内,但是,当先打开客户端时,有错误;先打开服务器时,正常。其中,线程内代码如下:unit SendThread;interface
uses Classes,SysUtils,Controls,Windows,IdComponent,IdUDPClient,ComCtrls,MainForm;
type TDelectThread=class(TThread)
private
IdUDPC:TIdUDPClient;
LV:TListView;
protected
procedure ExeCute;override;
public
constructor Create(IdUDPC1:TIdUDPClient;LV1:TListView);
destructor Destroy;override;
end;
implementation{ TDelectThread }constructor TDelectThread.Create(IdUDPC1: TIdUDPClient; LV1: TListView);
begin
IdUDPC:=IdUDPC1;
LV:=LV1;
inherited Create(False);
end;destructor TDelectThread.Destroy;
begin
inherited Destroy;
end;procedure TDelectThread.ExeCute;
var ReceiveString,RemoteIP:String;
j:Integer;
begin
//inherited;
FreeOnTerminate:=True;
if WaitForSingleObject(hMutex,INFINITE)=WAIT_OBJECT_0 then
begin
if IdUDPC.Active<>True then Exit;
IdUDPC.Send('GetIp');//此时客户机上如果收到此信息,就把ip地址传过来
RemoteIP:=IdUDPC.ReceiveString();
sum:=i;
try
if RemoteIP<>'' then
begin
for j:=0 to sum-1 do //????????
begin
*************************************************
if RemoteIP=LV.Items[j].Caption then Exit //如果先运行客户端,最后再运行服务器端,此处出错****************************************
else
continue;
end;
LV.Items.Add;
LV.Items[i].Caption:=RemoteIP;
Inc(i);
end;
except
IdUDPC.Active:=False;
end;
end;
ReleaseMutex(hMutex);
end;end.
错误出在
if RemoteIP=LV.Items[j].Caption 这句。请指教?
uses Classes,SysUtils,Controls,Windows,IdComponent,IdUDPClient,ComCtrls,MainForm;
type TDelectThread=class(TThread)
private
IdUDPC:TIdUDPClient;
LV:TListView;
protected
procedure ExeCute;override;
public
constructor Create(IdUDPC1:TIdUDPClient;LV1:TListView);
destructor Destroy;override;
end;
implementation{ TDelectThread }constructor TDelectThread.Create(IdUDPC1: TIdUDPClient; LV1: TListView);
begin
IdUDPC:=IdUDPC1;
LV:=LV1;
inherited Create(False);
end;destructor TDelectThread.Destroy;
begin
inherited Destroy;
end;procedure TDelectThread.ExeCute;
var ReceiveString,RemoteIP:String;
j:Integer;
begin
//inherited;
FreeOnTerminate:=True;
if WaitForSingleObject(hMutex,INFINITE)=WAIT_OBJECT_0 then
begin
if IdUDPC.Active<>True then Exit;
IdUDPC.Send('GetIp');//此时客户机上如果收到此信息,就把ip地址传过来
RemoteIP:=IdUDPC.ReceiveString();
sum:=i;
try
if RemoteIP<>'' then
begin
for j:=0 to sum-1 do //????????
begin
*************************************************
if RemoteIP=LV.Items[j].Caption then Exit //如果先运行客户端,最后再运行服务器端,此处出错****************************************
else
continue;
end;
LV.Items.Add;
LV.Items[i].Caption:=RemoteIP;
Inc(i);
end;
except
IdUDPC.Active:=False;
end;
end;
ReleaseMutex(hMutex);
end;end.
错误出在
if RemoteIP=LV.Items[j].Caption 这句。请指教?
[email protected]
begin
if RemoteIP=LV.Items[j].Caption then Exit
end;
TListView是非线程安全的,
Synchronize(test)
凡是在线程中遇到VCL,都要用Synchronize来同步