-1

我一直在尝试在 tcp 上发送消息,但是这些代码似乎在 Delphi 7 上给出了奇怪的错误,我在 Delphi XE 上尝试了类似的代码,它工作正常。我在 XE 和 Delphi 7 上都使用 Indy 10。

type
  TClient   = class(TIdContext) 
    PeerIP      : String;          
    RcvdMsg     : String;

    procedure SendResponse(const AResponse: String);
  end;

...

procedure TForm1.IdTCPServer1Connect(AContext: TIdContext);
var
  NewClient:   TClient;
begin
  with TClient(AContext) do
  begin
    NewClient.PeerIP      := Connection.Socket.Binding.PeerIP;
    NewClient.RcvdMsg     := Connection.Socket.ReadLn;
  end;
end;

...

procedure TForm1.BitBtn1Click(Sender: TObject);
var
  Context: TClient;
  List: TList;
  I: Integer;
begin

  List := IdTCPServer1.Contexts.LockList;
  try
    for I := 0 to List.Count-1 do
    begin
      Context := TClient(List[I]);
      MessageBox(0,pChar(Context.PeerIP),0,0); // shows wierd string
 (*     if (Context.PeerIP = IP) then
      begin 
        //didn't get to here
        Context.SendResponse('msg');
        Break;
      end              *)

    end;
  finally
    IdTCPServer1.Contexts.UnlockList;
  end;
end;

有什么办法解决吗?

编辑:

type
      TClient   = class(TIdServerContext) 
        PeerIP      : String;          
        RcvdMsg     : String;

        procedure SendResponse(const AResponse: String);
      end;

procedure TForm1.FormCreate(Sender: TObject);
begin

  IdTCPServer1.Bindings.Add.Port := 1234;
  IdTCPServer1.Active := not IdTCPServer1.Active;
  IdTCPServer1.ContextClass := TClient;
end;

我仍然无法发送消息。

procedure TForm1.BitBtn1Click(Sender: TObject);
    var
      Context: TClient;
      List: TList;
      I: Integer;
    begin

      List := IdTCPServer1.Contexts.LockList;
      try
        for I := 0 to List.Count-1 do
        begin
          Context := TClient(List[I]);
          MessageBox(0,pChar(Context.PeerIP),0,0); // blank
     (*     if (Context.PeerIP = IP) then
          begin 
            //didn't get to here
            Context.SendResponse('msg');
            Break;
          end              *)

        end;
      finally
        IdTCPServer1.Contexts.UnlockList;
      end;
    end;
4

1 回答 1

2

TClient需要派生自TIdServerContext,而不是TIdContext。如果您还没有这样做,请确保TIdTCPServer.ContextClass在激活服务器之前分配属性,否则您的类型转换将无效:

type
  TClient = class(TIdServerContext)
    ...
  end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  IdTCPServer1.ContextClass := TClient;
  ...
end;
于 2013-10-27T19:40:00.597 回答