Building a Server Application in Delphi - Building a Server application
(Page 5 of 5 )
There are two ways to built a server application in Indy: command handlers and through the OnExecute event.
Command handlers are mostly suited to text-based protocols. They enable you to set up your own protocol and implement it. Most protocols are text-based and can be used with the command handlers format, but are not suited to protocols which have a binary command structure or no command structure. Below is an example command handler that implements a command called "gettxt":
procedure TForm1.IdTCPServer1TIdCommandHandler1gettxt(ASender: TIdCommand);
var
receivedtxt: string;
begin
if ASender.Params.Count > 0 then begin
receivedtxt := ASender.Params[0];
end;
ASender.Reply.Text.Text := receivedtxt;
end;
OnExecute Event
For servers that have a binary command structure or no command structure, the OnExecute event should be used. The OnExecute event runs for as long as there is a live connection. Here's an example:
procedure TForm1.IdTCPServer1Execute(AThread: TIdPeerThread);
var
ACmd: string;
begin
with AThread.Connection do begin
ACmd := Trim(ReadLn);
if SameText(ACmd, 'Hi') then begin
WriteLn('200 Hi to you too');
Disconnect;
end else if SameText(ACmd, 'DATE') then begin
WriteLn('200 ' + DateToStr(Date));
end else begin
WriteLn('400 Unknown command');
end;
end;
end;
You can see in the code above that I do not check for a connection nor do I do any looping. Both are done by Indy automatically. Indy repeatedly calls this event until there is no connection. This can be caused by the client disconnecting, or a disconnect call as above.
Conclusion
I've read extensively on both Delphi and indy threading models, but have not covered it all here. So if you want to learn more about indy components and the like, a excellent source is the "Indy in Depth" ebook. It tells you everything about how indy components work and in what situations you can use them.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |