加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 10:14:33 所属栏目:大数据 来源:网络整理
导读:在以下情况下,如何使用Indy的TIdTCPClient和TIdTCPServer? Client ---------- initate connection ----------- Server...Client ---------------command------------------- ServerClient ----------------response----------------- Server...Client ----
在以下情况下,如何使用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语句等到有数据。这就是这一切的魔力。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读