没有什么能够阻止你使用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
下面是输出:
你叫什么名字?
马库斯
你好,马库斯。
你想玩游戏吗?
与主机连接丢失。
没有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陈述等到有数据。这是所有背后的魔力。
也许你可以用'IdTCPClient1.IOHandler.ReadLnWait'或'IdTCPClient1.IOHandler.WaitFor'方法来模拟这种行为。否则,使用'TIdCmdTCPCLient'可以解决你的问题。 – LightBulb
哪个版本的Indy? –
目前,我在德尔福2010年使用Indy 10。 – LightBulb