{
author:cxg
断网自动检查并提示,自动重连
}
unit ClientTestConnected;
interface
uses
SysUtils, Classes, SqlExpr,uNetCommon;
type
TWaitThread = class(TThread)
private
{ Private declarations }
fNetConnect:Boolean;
FCheckInterval: Integer;
FMsg: string;
protected
procedure ShowMsg;
procedure Execute; override;
procedure ServerOpen;
procedure ServerClose;
function ConnRemoteSvr(cn:TSQLConnection;const hostname,UserName,password:string;
const port:Integer):Boolean;
public
NetCheck1: TNetCheck;
constructor Create(const ACheckInterval: Integer);
destructor Destroy; override;
procedure CheckNetConnect(Sender: TObject; var objWbemObject,
objWbemAsyncContext: OleVariant);
procedure CheckNetDisconnect(Sender: TObject; var objWbemObject,
objWbemAsyncContext: OleVariant);
end;
implementation
uses ClientForm;
procedure TWaitThread.ServerClose;
begin
FrmMain.SQLConnection1.Close;
end;
procedure TWaitThread.ServerOpen;
begin
if fNetConnect then
FMsg := '正在连接...'
else FMsg :='网络异常';
Synchronize(ShowMsg);
if ConnRemoteSvr(FrmMain.SQLConnection1,'localhost','cxg','123',211) then
begin
FMsg := '网络正常';
Synchronize(ShowMsg);
end;
end;
procedure TWaitThread.ShowMsg;
begin
FrmMain.Label1.Caption := FMsg;
end;
procedure TWaitThread.Execute;
begin
try
ServerOpen;
fNetConnect :=True;
except
fNetConnect :=False;
end;
repeat
Sleep(FCheckInterval);
if not fNetConnect then
begin
FCheckInterval := 3000;
ServerClose;
ServerOpen;
end;
until Terminated;
end;
procedure TWaitThread.CheckNetConnect(Sender: TObject; var objWbemObject,
objWbemAsyncContext: OleVariant);
begin
fNetConnect := True;
end;
procedure TWaitThread.CheckNetDisconnect(Sender: TObject; var objWbemObject,
objWbemAsyncContext: OleVariant);
begin
fNetConnect :=False;
end;
function TWaitThread.ConnRemoteSvr(cn: TSQLConnection; const hostname, UserName,
password: string; const port: Integer): Boolean;
begin
try
cn.Close;
cn.DriverName := 'DataSnap';
cn.LoginPrompt :=False;
Cn.ConnectionName := 'DataSnapCONNECTION';
cn.Params.Clear;
cn.Params.Add('DriverName=DataSnap');
Cn.Params.Add('HostName='+HostName);
Cn.Params.Add('Port='+inttostr(port));
Cn.Params.Add('User_Name='+UserName);
Cn.Params.Add('Password='+PassWord);
cn.Open;
Result :=True;
except
Result :=False;
end;
end;
constructor TWaitThread.Create(const ACheckInterval: Integer);
begin
FCheckInterval := ACheckInterval;
NetCheck1 :=TNetCheck.Create(nil);
NetCheck1.OnNetWireConnect:=CheckNetConnect;
NetCheck1.OnNetWireDisconnect:=CheckNetDisconnect;
inherited Create(False);
end;
destructor TWaitThread.Destroy;
begin
NetCheck1.Free;
NetCheck1 :=nil;
inherited;
end;
end.