沒有什麼能夠阻止你使用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