如果客户端是TCP/IP是短连接的情况就没有必要了。
1 type 2 pClientConns = ^TClientConns; // 客户连接 3 TClientConns = record 4 clientid: integer; 5 ip: string; 6 port: string; 7 logintime: TDateTime; 8 end; 9 10 type 11 G_ClientConnects: TDictionary<TIdTCPConnection, pClientConns>; // 客户端连接字典 12 13 procedure TServerContainer1.DSTCPServerTransport1Connect 14 (Event: TDSTCPConnectEventObject); 15 var 16 p: pClientConns; 17 begin 18 try 19 if G_ConnnectCount >= G_MaxConnNum then 20 begin 21 LogInfo('已超过系统授权的客户连接数'); 22 TIdTCPConnection(Event.Connection).Disconnect; 23 exit; 24 end; 25 InterlockedIncrement(G_ConnnectCount); 26 New(p); 27 if Assigned(p) then 28 begin 29 p^.clientid := Event.Channel.ChannelInfo.Id; 30 p^.ip := Event.Channel.ChannelInfo.ClientInfo.IpAddress; 31 p^.port := Event.Channel.ChannelInfo.ClientInfo.ClientPort; 32 p^.logintime := Now; 33 G_ClientConnects.Add(TIdTCPConnection(Event.Connection), p); 34 PostMessage(Application.MainForm.Handle, WM_ADDUSER, wParam(p), 35 lParam(TIdTCPConnection(Event.Connection))); 36 end; 37 except 38 exit; 39 end; 40 end; 41 42 procedure TServerContainer1.DSTCPServerTransport1Disconnect 43 (Event: TDSTCPDisconnectEventObject); 44 var 45 p: pClientConns; 46 begin 47 try 48 if G_ConnnectCount >= 1 then 49 InterlockedDecrement(GlobalVar.G_ConnnectCount); 50 p := G_ClientConnects.Items[TIdTCPConnection(Event.Connection)]; 51 if Assigned(p) then 52 begin 53 SendMessage(Application.MainForm.Handle, WM_DELUSER, wParam(p), 0); 54 G_ClientConnects.Remove(TIdTCPConnection(Event.Connection)); 55 end; 56 except 57 exit; 58 end; 59 end; 60 61 procedure Tf_MainForm.AddUser(var msg: TMessage); 62 var 63 p: pClientConns; 64 begin 65 try 66 Label4.Caption := IntToStr(G_ConnnectCount); 67 p := pClientConns(msg.WParam); 68 if Assigned(p) then 69 begin 70 ClientDataSet1.Append; 71 ClientDataSet1.FieldByName('id').AsInteger := p^.clientid; 72 ClientDataSet1.FieldByName('ip').AsString := p^.ip; 73 ClientDataSet1.FieldByName('port').AsString := p^.port; 74 ClientDataSet1.FieldByName('time').AsDateTime := p^.logintime; 75 ClientDataSet1.FieldByName('conn').AsInteger := msg.LParam; 76 ClientDataSet1.Post; 77 end; 78 except 79 on E: Exception do 80 begin 81 LogInfo('Tf_MainForm.AddUser---' + E.Message); 82 exit; 83 end; 84 end; 85 end; 86 87 procedure Tf_MainForm.DelUser(var msg: TMessage); 88 var 89 p: pClientConns; 90 begin 91 try 92 Label4.Caption := IntToStr(G_ConnnectCount); 93 p := pClientConns(msg.WParam); 94 if Assigned(p) then 95 begin 96 if ClientDataSet1.FindKey([p^.clientid]) then 97 ClientDataSet1.Delete; 98 Dispose(p); 99 end; 100 except 101 on E: Exception do 102 begin 103 LogInfo('Tf_MainForm.DelUser---' + E.Message); 104 exit; 105 end; 106 end; 107 end;