ctBlocking要放入线程。
两个单元:Unit1.pas:主程序;MyThread.pas:线程的主程序;
//Unit1.pas
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ScktComp, MyThread;
type
TMainForm = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
tmBegin : TTime;
CT: TMyThread;
CTActive: Boolean;
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
procedure TMainForm.Button1Click(Sender: TObject);
var
iTimeOut: Integer;//从Open到现在经过的秒数
begin
CT := TMyThread.CreateIt;
tmBegin := Time;
CTActive := True;
CT.Resume;
while (CT <> nil) and (CTActive) and (not CT.CS.Active) do
begin
iTimeOut := StrToInt(FormatDateTime('ns' , Time - tmBegin));
if iTimeOut >= 5 then//超时5秒
begin
CT.Terminate;
MessageBox(Handle, PChar('因为超时,无法连接到目的计算机.'), '连接失败...', MB_ICONERROR);
Exit;
end;
end;
end;
procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if CT <> nil then CT.Terminate;
end;
end.
//MyThread.pas
unit MyThread;
interface
uses
Classes, comctrls, ScktComp, Dialogs;
type
TMyThread = class(TThread)
private
FCS: TClientSocket;
procedure CSConnect(Sender: TObject; Socket: TCustomWinSocket);
procedure CSError(Sender: TObject; Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent; var ErrorCode: Integer);
protected
procedure Execute; override;
public
constructor CreateIt;
destructor Destroy; override;
published
property CS: TClientSocket read FCS write FCS;
end;
var
MyThread1: TMyThread;
implementation
{ TMyThread }
constructor TMyThread.CreateIt;
begin
Inherited Create(False);
FCS := TClientSocket.Create(nil);
end;
procedure TMyThread.CSConnect(Sender: TObject; Socket: TCustomWinSocket);
begin
ShowMessage('Connected!');
end;
procedure TMyThread.CSError(Sender: TObject; Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent; var ErrorCode: Integer);
begin
ErrorCode := 0;
case ErrorEvent of
eeConnect: showMessage('Error in connecting');
else
end;
end;
destructor TMyThread.Destroy;
begin
if FCS.Active then FCS.Close;
FCS.Free;
inherited Destroy;
end;
procedure TMyThread.Execute;
begin
with FCS do
begin
OnConnect := MyThread1.CSConnect;
OnError := MyThread1.CSError;
ClientType := ctBlocking;
Address := '111.111.111.111';
Port := 9999;
Open;
end;
end;
end.