2013-10-27 79 views
-1

我一直在嘗試發送消息在tcp上,但這些代碼似乎給Delphi 7上的奇怪錯誤,你我在Delphi XE上試過類似的代碼,它工作正常。用印10兩個XE和Delphi林7在Delphi 7中通過TCP發送消息

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; 
+1

是輸出真正的「怪異字符串」 ? –

+0

我的意思是奇怪的ascii字符,或者我不知道你們叫什麼 – user1979304

回答

2

TClient需要從TIdServerContext,不TIdContext派生。並確保您激活服務器之前分配TIdTCPServer.ContextClass財產,如果你沒有這樣做,否則你的類型轉換將是無效的:

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

procedure TForm1.FormCreate(Sender: TObject); 
begin 
    IdTCPServer1.ContextClass := TClient; 
    ... 
end; 
+0

謝謝你的幫助,我居然試過'TIdServerContext',但結果是一樣的,如果加了IdTCPServer1也不行.ContextClass:= TClient;'...我編輯了我的文章 – user1979304

+0

在激活服務器之前,您必須設置'ContextClass' **,否則可能會導致客戶端連接到服務器並最終使用默認的'TIdServerContext'類在更新'ContextClass'之前使用您的自定義類。 –