Send command from TIdCmdTCPServer

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

To send a command from TIdCmdTCPServer in Indy (Internet Direct) component suite for Delphi or Lazarus, you need to use the SendCmd method. The TIdCmdTCPServer component allows you to build a simple command-based server.

Here's an example of how you can send a command from TIdCmdTCPServer:

  1. Place the TIdCmdTCPServer component on your form.
  2. Define the commands you want to handle by implementing the OnCommand event.
  3. Call the SendCmd method from the server to send a response to the client.

Below is a basic example of how to send a command from TIdCmdTCPServer:

delphi
procedure TForm1.IdCmdTCPServer1Connect(AContext: TIdContext);
begin
// This event is triggered when a client connects to the server
// You can send a welcome message or initial command to the client here
AContext.Connection.IOHandler.WriteLn('Welcome to the server!');
end;

procedure TForm1.IdCmdTCPServer1CommandHandlers0Command(
ASender: TIdCommand);
begin
// This event is triggered when a command is received from the client
// ASender is the command object, and ASender.Params contains the command parameters

// Process the command and generate a response
// For example, we can simply echo the received command back to the client
ASender.Context.Connection.IOHandler.WriteLn('You sent: ' + ASender.UnparsedParams);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
// Send a command from the server to the connected client
if IdCmdTCPServer1.Contexts.Count > 0 then
IdCmdTCPServer1.Contexts[0].Connection.IOHandler.WriteLn('Server command here');
end;

In this example, we have a TButton control on the form. When the button is clicked, the server sends the command "Server command here" to the first connected client (if any).

Make sure to adjust the server address and port appropriately in your client application to connect to the TIdCmdTCPServer.

Remember that TIdCmdTCPServer is a basic command handler, and it doesn't provide robust security features. If you are building a more complex application, consider implementing additional security measures and validation of incoming commands.