首先加入以下单元:
uses DBXCommon,IdTCPConnection,IdWinsock2;
再声明:
type
...
type
TCP_KeepAlive = record
OnOff: Cardinal;
KeepAliveTime: Cardinal;
KeepAliveInterval: Cardinal;
end;
....
在服务端的DSServer1.OnConnect事件中:
procedure TServerContainer2.DSServer1Connect(
DSConnectEventObject: TDSConnectEventObject);
var
Val: TCP_KeepAlive;
Ret: DWord;
conne:tidtcpconnection;
aip,aport,ausername,apass:string;
begin
//验证
conne:=TIdTCPConnection(DSConnectEventObject.ChannelInfo.Id);
aip:=conne.Socket.Binding.PeerIP;
aport:=inttostr(conne.Socket.Binding.PeerPort);
ausername:=DSConnectEventObject.ConnectProperties[TDBXPropertyNames.UserName];
apass:=DSConnectEventObject.ConnectProperties[TDBXPropertyNames.Password];
if (ausername<>'jiangbin') and (apass<>'2010') then
DSConnectEventObject.DbxConnection.Destroy
else
fr_main.memo1.Lines.add(aip+':'+aport+' 名称:'+ausername);
//心跳包代码
Val.OnOff := 1;
Val.KeepAliveTime := 5000;
Val.KeepAliveInterval := 3000;
WSAIoctl(conne.Socket.Binding.Handle, IOC_IN or IOC_VENDOR or 4,
@Val, SizeOf(Val), nil, 0, @Ret, nil, nil);
end;
然后在服务端的DSServer1.OnDisConnect事件中:
procedure TServerContainer2.DSServer1Disconnect(
DSConnectEventObject: TDSConnectEventObject);
var conne:tidtcpconnection;
aip,aport,ausername,apass:string;
i:integer;
begin
//断开后清除连接IP及端口
conne:=TIdTCPConnection(DSConnectEventObject.ChannelInfo.Id);
aip:=conne.Socket.Binding.PeerIP;
aport:=IntToStr(conne.Socket.Binding.PeerPort);
if fr_main.Memo1.Lines.Count>0 then
begin
for i:=0 to fr_main.Memo1.Lines.Count - 1 do
begin
if pos(aip+':'+aport,fr_main.Memo1.Lines[i])>0 then
fr_main.Memo1.Lines.Delete(i);
end;
end;
end;