如何获得delphi Xe2 Indy 10 socket服务器对等主机名

时间:2013-05-17 20:19:19

标签: delphi delphi-xe2 indy

这是我的代码......

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给出了我的服务器的名称,如何获取客户端主机名?

1 个答案:

答案 0 :(得分: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;