2013-05-17 27 views
0

這裏是我的代碼...如何讓德爾福XE2印10插槽服務器等主機名

procedure TMainForm.tsConnect(AContext: TIdContext); 
var 
    s, INstr, adr:string; 
    port: Integer; 
begin 
    with TMyContext(AContext) do 
    begin 
    Con := Now; 
    if (Connection.Socket <> nil) then 
     IP :=Connection.Socket.Binding.PeerIP; 
    port:=Connection.Socket.Binding.PeerPort; 
    s:=IntToStr(Connection.Socket.Binding.PeerPort); 
    TIdStack.IncUsage(); 
    try 
     adr:= GStack.HostName; 
    finally 
     TIdStack.DecUsage; 
    end; 

    INstr := Connection.IOHandler.ReadLn; 
    Nick := INstr; 

    if Nick <> '' then 
    begin 
     memo1.Lines.Add('Opened <'+Nick + '> '+adr+' '+IP+':'+s+'  '+DAteTimeToStr(now)); 
     //SendNicks; 
    end else 
    begin 
     Connection.IOHandler.WriteLn('No Nick provided! Goodbye.'); 
     Connection.Disconnect; 
    end; 
    end; 
end; 

GStack.HostName給我的服務器,如何讓客戶端主機名的名稱?

回答

3

使用TIdStack.HostByAddress()獲取客戶端的遠程主機名,如:

adr := GStack.HostByAddress(IP); 

雖這麼說,你不需要調用TIdStack.IncUsage()TIdStack.DecUsage()因爲TIdTCPServer處理,對於你在它的構造函數和析構函數,分別。但更重要的是,您直接訪問TMemo不是線程安全的。請記住TIdTCPServer是一個多線程組件。該OnConnect事件(OnDisconnectOnExecute運行在輔助線程,而不是主線程UI訪問必須在主線程,而不是做

試試這個:

procedure TMainForm.tsConnect(AContext: TIdContext); 
var 
    INstr, adr: string; 
    port: Integer; 
begin 
    with TMyContext(AContext) do 
    begin 
    Con := Now; 
    IP := Connection.Socket.Binding.PeerIP; 
    port := Connection.Socket.Binding.PeerPort; 

    adr := GStack.HostByAddress(IP); 

    INstr := Connection.IOHandler.ReadLn; 
    Nick := INstr; 

    if Nick <> '' then 
    begin 
     TThread.Synchronize(nil, 
     procedure 
     begin 
      memo1.Lines.Add('Opened <' + Nick + '> ' + adr + ' ' + IP + ':' + IntToStr(port) + '  ' + DateTimeToStr(Con)); 
     end 
    ); 
     //SendNicks; 
    end else 
    begin 
     Connection.IOHandler.WriteLn('No Nick provided! Goodbye.'); 
     Connection.Disconnect; 
    end; 
    end; 
end; 

或者:

uses 
    ..., IdSync; 

type 
    TMemoNotify = class(TIdNotify) 
    protected 
    FMsg: String; 
    procedure DoNotify; override; 
    end; 

procedure TMemoNotify.DoNotify; 
begin 
    MainForm.Memo1.Lines.Add(FMsg); 
end; 

procedure TMainForm.tsConnect(AContext: TIdContext); 
var 
    INstr, adr: string; 
    port: Integer; 
begin 
    with TMyContext(AContext) do 
    begin 
    Con := Now; 
    IP := Connection.Socket.Binding.PeerIP; 
    port := Connection.Socket.Binding.PeerPort; 

    adr := GStack.HostByAddress(IP); 

    INstr := Connection.IOHandler.ReadLn; 
    Nick := INstr; 

    if Nick <> '' then 
    begin 
     with TMemoNotify.Create do 
     begin 
     FMsg := 'Opened <' + Nick + '> ' + adr + ' ' + IP + ':' + IntToStr(port) + '  ' + DateTimeToStr(Con); 
     Notify; 
     end; 
     //SendNicks; 
    end else 
    begin 
     Connection.IOHandler.WriteLn('No Nick provided! Goodbye.'); 
     Connection.Disconnect; 
    end; 
    end; 
end;