繁体   English   中英

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

[英]How to set up a simple connection between TIdTcpClient and TIdTcpServer to send a string from client to server?

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

多谢您的协助。

服务器:
创建,初始化函数中的任何位置:

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!');

由于该问题特别询问如何从VCL组件发送到另一个VCL组件,并且很可能会再次询问/搜索此问题。
使用IdTCPClient非常容易。
您只需要分配Host和Port,打开连接,然后将内容写入IdTCPClient的套接字即可。
因为您将必须能够在服务器端读取数据并且不需要协议(例如,将内容的长度作为整数发送以使服务器知道他必须读取多少内容),所以最简单的方法是使用Socket.WriteLn可以在服务器端使用Socket.ReadLn
请注意, OnExecute事件在自己的IdTCPServer中运行,因此您必须将对调用的同步化到主线程。
执行此操作的一种可能方法是使用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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM