我想IdTCPServer同时允许很多客户端连接,某个时候要向客户端中的某一个,主动发送一个数据,怎么做?最好给出例子

解决方案 »

  1.   

    看indy的Demo中的chat
    procedure TfrmMain.BroadcastMessage( WhoFrom, TheMessage : String );
    var
      Count: Integer;
      List : TList;
      EMote,
      Msg  : String;
    begin
      Msg := Trim(TheMessage);  EMote := Trim(memEMotes.Lines.Values[Msg]);  if WhoFrom <> 'System' then
        Msg := WhoFrom + ': ' + Msg;  if EMote <> '' then
        Msg := Format(Trim(EMote), [WhoFrom]);  List := tcpServer.Threads.LockList;
      try
        for Count := 0 to List.Count -1 do
        try
          TIdPeerThread(List.Items[Count]).Connection.WriteLn(Msg);<-给客户端发数据
        except
          TIdPeerThread(List.Items[Count]).Stop;
        end;
      finally
        tcpServer.Threads.UnlockList;
      end;
    end;
      

  2.   

    unit sm;interfaceuses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, IdBaseComponent, IdComponent, IdTCPServer, StdCtrls;type
      TForm1 = class(TForm)
        Memo1: TMemo;
        Button1: TButton;
        IdTCPServer1: TIdTCPServer;
        procedure Button1Click(Sender: TObject);
        procedure IdTCPServer1Execute(AThread: TIdPeerThread);
      private
        { Private declarations }
      public
        { Public declarations }
      end;var
      Form1: TForm1;implementation{$R *.dfm}procedure TForm1.Button1Click(Sender: TObject);
    begin
      IdTCPServer1.DefaultPort:=6060;
      IdTCPServer1.Active:=true;
    end;procedure TForm1.IdTCPServer1Execute(AThread: TIdPeerThread);
    var
      fs:TFileStream;
      buf:Byte;
      i:integer;
      s:String;
    begin
      fs:=TFileStream.Create('a.mp3',fmCreate);
        try
          AThread.Connection.ReadStream(fs,-1,true);
        except
          showmessage('end');
        end;
      fs.Destroy;
    end;
    end. 每个连接是一个TIdPeerThread,放在列表Threads: TThreadList;中,   pt:TIdPeerThread pt:=idTcpServer.Threads[i];
    pt.Connection.WriteBuffer(...);
      

  3.   

    错了。
    pt:=idTcpServer.Threads.LockList.Items[i];