Using the Command Handler Method in Delphi
(Page 1 of 5 )
In the previous article, we discussed the various ways in which we can create indy servers. Picking up from where we left off, in this article we are going to build a server application using the CommandHandler method.
A
downloadable zip file is available for this article.
Let's create a example server application using the Command handler method. We will use telnet as the client that will access the server. Our protocol will consist of three commands:
- Quit - Closes down the connection.
- Adate - Gets today's date.
- Aquote - Displays a random quote from an array.
Create a new application and drop an idCMDTCPServer component (available from the IndyServers tab) onto the form. Click on the component and go to the object inspector's properties tab.

Click on the CommandHandlers property ellipses button. You should now see the following window:

Click on the yellow folder at the top left. The options on the object inspector should know be changed, and you should see in the editor box something like "TidCommandHandler0." Now, go to the object inspectors properties tab, find the property called "command," and call it "Aquote":

After you've done that, go to the events tab of the object inspector and double click on the Oncommand event. Add the following code:
procedure TForm1.IdCmdTCPServer1CommandHandlers0Command(
ASender: TIdCommand);
var
i : Integer;
arr:Array[1..6] of String;
begin
Randomize;
arr[1]:='I still miss my ex, but my aim is improving';
arr[2]:='Last night I was looking up at the stars and I was
wondering, where the heck is my ceiling?';
arr[3]:='Do Roman paramedics refer to IVs as fours?';
arr[4]:='I can resist everything except temptation.';
arr[5]:='There is one thing I would break up over and that is
if she caught me with another woman. I wouldn''t stand for
that.';
arr[6]:='I''ve often thought that the process of aging could be
slowed down if it had to go through Congress.'+#13#10+'George
Bush';
// Get an integer random number in the range 1..6
i:=1+ Random(6);
ASender.Context.Connection.IOHandler.WriteLn(arr[i]);
end;
The procedure above is quite simple. I've put various quotes into an array which is using the random function to show different quotes every time a client request is received. To write the quote back to the client, we use the client context, as in:
ASender.Context.Connection.IOHandler.WriteLn(arr[i]);
Next: Implementing the Second and Third Commands >>
More Delphi-Kylix Articles
More By Leidago