如何在TIdTcpClient和TIdTcpServer之间建立一个简单的连接,以便从客户端向服务器发送字符串?

时间:2014-10-29 11:46:21

标签: windows delphi indy

我正在使用Delphi xe6来阻止简单的客户端/服务器连接。客户端表单应具有TEdit组件,并应将Edit.text字符串发送到服务器备忘录。我想使用Indy组件:TIdTcpServer和TIdTcpClient但我不知道如何在客户端和服务器之间建立简单的连接。

感谢您的帮助。

2 个答案:

答案 0 :(得分:5)

服务器
Create,Initialize函数中的任何位置:

FIndySrv:=TIdTCPServer.Create(nil);
FIndySrv.DefaultPort:=50000;
FIndySrv.OnExecute:=DoOnIndyExecute;
FIndySrv.Active:=true;

OnExecute:

procedure TForm1.DoOnIndyExecute(AContext: TIdContext);
var recv:string;
begin
  recv := AContext.Connection.Socket.ReadLn;
  // ...
end;

客户:

FIndyClient:=TIdTCPClient.Create(nil);
FIndyClient.Host:='localhost';
FIndyClient.Port:=50000;
FIndyClient.Connect;
FIndyClient.Socket.WriteLn('Hallo Welt!');

答案 1 :(得分:0)

由于问题特别询问如何从VCL组件发送到另一个VCL组件,并且可能会再次询问/搜索此问题。
使用IdTCPClient就像它一样容易 您只需分配主机和端口即可 ,打开连接并将内容写入IdTCPClient的套接字 因为你必须能够在服务器端读取数据而没有 需要一个协议(例如,将内容的长度作为整数发送,让服务器知道他必须阅读多少) 最简单的方法是使用Socket.WriteLn在服务器端使用Socket.ReadLn 请注意,OnExecute IdTCPServer事件在自己的threadcontext中运行,因此您必须将调用与主线程同步。
其中一种可能的方法是使用TIDSync的后代。

uses IDSync;

type
  TMySync = Class(TIDSync)
  private
    FContent: String;
    FDestination: TStrings;
    Constructor Create(const Content: String; Destination: TStrings); overload;
  protected
    Procedure DoSynchronize; override;
  public
  End;

constructor TMySync.Create(const Content: String; Destination: TStrings);
begin
  inherited Create;
  FContent := Content;
  FDestination := Destination;
end;

procedure TMySync.DoSynchronize;
begin
  inherited;
  FDestination.Add(FContent);
end;

procedure TaForm.Button1Click(Sender: TObject);
begin
  if not IdTCPClient.Connected then
    IdTCPClient.Connect;
  IdTCPClient.Socket.WriteLn(Edit.Text);
end;

procedure TaForm.FormCreate(Sender: TObject);
const
  // the port which will be used for Server and Client
  C_PORT = 12345;
begin
  IdTCPServer.DefaultPort := C_PORT;
  IdTCPServer.Active := true;
  IdTCPClient.Host := '127.0.0.1';
  IdTCPClient.Port := C_PORT;
end;

procedure TaForm.IdTCPServerExecute(AContext: TIdContext);
begin
  With TMySync.Create(AContext.Connection.Socket.ReadLn, Memo.Lines) do
  begin
    Synchronize;
    Free;
  end;
end;