delphi – Indy TCP客户端/服务器与客户端充当服务器

在以下情况下,如何使用Indy的TIdTCPClient和TIdTcpserver?
Client  ---------- initate connection -----------> Server
...
Client  <---------------command------------------- Server
Client  ----------------response-----------------> Server
...
Client  <---------------command------------------- Server
Client  ----------------response-----------------> Server

客户端启动连接,但作为“服务器”(等待命令并执行它们)。

在这种情况下,TIdTcpserver的OnExecute方法不能正常工作(至少我没有得到很好的效果)。我该怎么做?

我希望这个问题足够清楚。

解决方法

没有什么可以阻止你这样做与Indy的TIdTcpserver组件。

TIdTcpserver仅设置连接。你需要实现其余的。所以实际发送和接收的顺序可以是任何你想要的。

将此代码放在TIdTcpserver组件的OnExecute事件中:

var
  sName: String;
begin
  // Send command to client immediately after connection
  AContext.Connection.socket.WriteLn('What is your name?');
  // Receive response from client
  sName := AContext.Connection.socket.ReadLn;
  // Send a response to the client
  AContext.Connection.socket.WriteLn('Hello,' + sName + '.');
  AContext.Connection.socket.WriteLn('Would you like to play a game?');
  // We're done with our session
  AContext.Connection.disconnect;
end;

以下是您可以简单地设置TIdTcpserver的方法

IdTcpserver1.Bindings.Clear;
IdTcpserver1.Bindings.Add.SetBinding('127.0.0.1',8080);
IdTcpserver1.Active := True;

这告诉服务器仅在端口8080上监听环回地址。这样可以防止计算机外的任何人连接到它。

然后,要连接您的客户端,您可以转到Windows命令提示符并键入以下内容

telnet 127.0.0.1 8080

以下是输出

What is your name?

marcus

Hello,marcus.

Would you like to play a game?

Connection to host lost.

没有telnet?以下是install telnet client on Vista and 7

或者使用TIdTCP客户端,您可以执行以下操作:

var
  sPrompt: String;
  sResponse: String;
begin
  // Set port to connect to
  IdTCPClient1.Port := 8080;
  // Set host to connect to
  IdTCPClient1.Host := '127.0.0.1';
  // Now actually connect
  IdTCPClient1.Connect;
  // Read the prompt text from the server
  sPrompt := IdTCPClient1.socket.ReadLn;
  // Show it to the user and ask the user to respond
  sResponse := InputBox('Prompt',sPrompt,'');
  // Send user's response back to server
  IdTCPClient1.socket.WriteLn(sResponse);
  // Show the user the server's final message
  ShowMessage(IdTCPClient1.socket.AllData);
end;

这里要注意的一个重要事情是ReadLn语句等到有数据。这就是这一切的魔力。

相关文章

 从网上看到《Delphi API HOOK完全说明》这篇文章,基本上都...
  从网上看到《Delphi API HOOK完全说明》这篇文章,基本上...
ffmpeg 是一套强大的开源的多媒体库 一般都是用 c/c+&#x...
32位CPU所含有的寄存器有:4个数据寄存器(EAX、EBX、ECX和ED...
1 mov dst, src dst是目的操作数,src是源操作数,指令实现的...