ClIEnt ---------- initate connection -----------> Server...ClIEnt <---------------command------------------- ServerClIEnt ----------------response-----------------> Server...ClIEnt <---------------command------------------- ServerClIEnt ----------------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 – Indy TCP客户端/服务器与客户端充当服务器全部内容,希望文章能够帮你解决delphi – Indy TCP客户端/服务器与客户端充当服务器所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)