[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 52481
  • Last Modified:

Indy TCP (Client/Server)

Greetings...
I Need a very Clear example of how to send & receive(commands and string)using indy TCP Client, Server Client ?
also the Server has a password to establish the connection from the client.
thank you for your time.
0
TheLeader
Asked:
TheLeader
1 Solution
 
alsantosCommented:
I think that it's a lot of work to a few points.

alsantos :)
0
 
TheLeaderAuthor Commented:
I already Increased it, and if it a lot of works, theres no worry to increased it again ;)
0
 
huferryCommented:
For the server:
- put TIdTCPServer component on your form
- adjust the port setting on the property inspector.
- for auto activation, set the property Active to True on the property inspector.
- Indy TCP server works in command/response mechanism, to add a command in your protocol,
  click on property CommandHandlers property on your property inspector then add your commands there.
- On each Command you can define the command string and use the OnCommand event to define
  your own actions.
- You can also use response (numericcode, text, etc) to standardize your responses.

Run your test server and test it first with a telnet application connecting to the defined ports.

For the client:
- Try the ReadLn and WriteLn methods from the TIdTCPClient component to read/write strings
   from/to the server.

An example code is more difficult to be read... this explanation will help more, I think.

regards,
huferry
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Lee_NoverCommented:
how about checking the examples ?
basic Chat should be enough
0
 
TheLeaderAuthor Commented:
ok I will try it "huferry"
but what about the server password ?

"Lee_Nover"
chat example(string) will be good but what about the commands & the server password !
0
 
alsantosCommented:
Hi, TheLeader, it isn't what I expect, but I'll help you.

he server code, it only answer to authenticated user. The user have to send the command "Password alsantos" to authenticate. If send any other command before authenticate, the server disconnect the user. You have to add 2 commandhandlers, On the idTcpServer1, click on CommandHandlers, and add 2 TIdCommandHandler with name Password and Time and Command "Password" and "Time" respectly. "The OnCommand" event of Password will call the procedure TForm1.IdTCPServer1PasswordCommand(ASender: TIdCommand) and the Time will call procedure TForm1.IdTCPServer1TimeCommand(ASender: TIdCommand); .  Now, the full source code of the server :)

unit u_Server;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, IdBaseComponent, IdComponent, IdTCPServer, StdCtrls;

type
  TForm1 = class(TForm)
    IdTCPServer1: TIdTCPServer;
    Button1: TButton;
    Edit1: TEdit;
    lbProcesses: TListBox;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure IdTCPServer1TimeCommand(ASender: TIdCommand);
    procedure IdTCPServer1NoCommandHandler(ASender: TIdTCPServer;
      const AData: String; AThread: TIdPeerThread);
    procedure IdTCPServer1Connect(AThread: TIdPeerThread);
    procedure FormCreate(Sender: TObject);
    procedure IdTCPServer1PasswordCommand(ASender: TIdCommand);
    procedure IdTCPServer1Disconnect(AThread: TIdPeerThread);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  Authenticated: TStringList;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  try
    IdTcpServer1.DefaultPort:=StrToInt(Edit1.Text);
    IdTCPServer1.Active := true;
    lbProcesses.Items.Append('Server started');
  except on E : Exception do
      lbProcesses.Items.Append('Server not started');
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  IdTCPServer1.Active := false;
  lbProcesses.Items.Append('Server stopped');
end;

procedure TForm1.IdTCPServer1TimeCommand(ASender: TIdCommand);
begin
  if Authenticated.IndexOf(ASender.Thread.Connection.LocalName) >= 0 then
    ASender.Thread.Connection.WriteLn(FormatDateTime('hh:nn:ss',now))
  else begin
    ASender.Thread.Connection.WriteLn('User not authenticated. Closed');
    ASender.Thread.Connection.Disconnect;
  end;
end;

procedure TForm1.IdTCPServer1NoCommandHandler(ASender: TIdTCPServer;
  const AData: String; AThread: TIdPeerThread);
begin
  if Authenticated.IndexOf(AThread.Connection.LocalName) >= 0 then
    AThread.Connection.WriteLn('Command not recognised - try again!')
  else begin
    AThread.Connection.WriteLn('User not authenticated. Closed');
    AThread.Connection.Disconnect;
  end;
end;

procedure TForm1.IdTCPServer1Connect(AThread: TIdPeerThread);
begin
  AThread.Connection.WriteLn('Welcome to my server. You have to send the password:');
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Authenticated:=TStringList.Create;
end;

procedure TForm1.IdTCPServer1PasswordCommand(ASender: TIdCommand);
begin
  if ASender.Params.Strings[0] = 'alsantos' then
  begin
    Authenticated.Add(ASender.Thread.Connection.LocalName);
    ASender.Thread.Connection.WriteLn('Password accepted.');
    lbProcesses.Items.Add('User authenticated: ' + ASender.Thread.Connection.LocalName );
  end
  else begin
    lbProcesses.Items.Add('User not authenticated: ' + ASender.Thread.Connection.LocalName );
    ASender.Thread.Connection.WriteLn('User not authenticated. Closed');
    ASender.Thread.Connection.Disconnect;
  end;
end;

procedure TForm1.IdTCPServer1Disconnect(AThread: TIdPeerThread);
begin
  if Authenticated.IndexOf(AThread.Connection.LocalName) >= 0 then
    Authenticated.Delete(Authenticated.IndexOf(AThread.Connection.LocalName));
  lbProcesses.Items.Add('User disconnected: ' + AThread.Connection.LocalName );
end;

end.
0
 
alsantosCommented:
now, the client side, it's more simple to understand.

unit u_Client;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, IdBaseComponent, IdComponent, IdTCPConnection,
  IdTCPClient;

type
  TForm1 = class(TForm)
    IdTCPClient1: TIdTCPClient;
    Button1: TButton;
    Button2: TButton;
    lbCommunication: TListBox;
    Edit1: TEdit;
    Edit2: TEdit;
    Edit3: TEdit;
    Button3: TButton;
    Button4: TButton;
    procedure Button2Click(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure IdTCPClient1Disconnected(Sender: TObject);
    procedure IdTCPClient1Connected(Sender: TObject);
    procedure Button4Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button2Click(Sender: TObject);
begin
  if IdTCPClient1.Connected then
    try
      IdTCPClient1.Disconnect;
    except on E : Exception do
      ShowMessage(E.Message);
    end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  lbCommunication.Items.Clear;
  with IdTCPClient1 do
  begin
    Host := Edit1.Text;
    Port := StrToint(Edit2.Text);
    try
      Connect;
      lbCommunication.Items.Add(idTCPClient1.ReadLn);
      except on E : Exception do
         ShowMessage(E.Message);
      end;
  end;
end;

procedure TForm1.Button3Click(Sender: TObject);
var
  LCommand, LInString : String;
begin
  LCommand := Edit3.Text;

  with IdTCPClient1 do
  begin
    try
      WriteLn(LCommand);
      LInString := ReadLn;

      lbCommunication.Items.Insert(0,'We Send -> ' + LCommand);
      lbCommunication.Items.Insert(0,'Server Send -> ' + LInString);

      except
      on E : Exception do
        ShowMessage(E.Message);
      end;
  end;
end;

procedure TForm1.IdTCPClient1Disconnected(Sender: TObject);
begin
  lbCommunication.Items.Insert(0,'Disconnected from remote server');
end;

procedure TForm1.IdTCPClient1Connected(Sender: TObject);
var
    LString : String;
begin
  LString := IdTCPClient1.ReadLn;
  lbCommunication.Items.Insert(0,'Connected to remote server');
  lbCommunication.Items.Insert(0,'Server send -> ' + LString);
end;

procedure TForm1.Button4Click(Sender: TObject);
begin
  with IdTCPClient1 do
  begin
    try
      WriteLn('Password alsantos');

      lbCommunication.Items.Insert(0,'We send the password alsantos');
      lbCommunication.Items.Insert(0,'Server send -> ' + ReadLn);

      except
      on E : Exception do
        ShowMessage(E.Message);
      end;
  end;
end;

end.

alsantos ;)
0
 
alsantosCommented:
If you want, I can send the source code for your email.

alsantos
0
 
TheLeaderAuthor Commented:
yes I would like to
mido@ksaguys.com
0
 
TheLeaderAuthor Commented:
"Alsantos" your code is perfect thank you :)
but could you explain what do you mean by
except on E : Exception do
when it will do the except ?
0
 
emu10k1Commented:
Thanks TheLeader...

I use try/except to protect the code. So, I use:

Try
    .... // it will try the code here, but it can generate an error, for example
          // the IdTCPClient1 isn't connected to a server.
          // so it will generate an error and the Except will catch this error
          // and show a message on the screen with the cause of this error
    { here the code that can generate an exception(error) }
Except
  On E: Exception do
           showmessage(E.Message); { here catch the error an show the error message }

alsantos
0
 
alsantosCommented:
I wrote this comment at friend's house. But it's me.
alsantos :)
0
 
alsantosCommented:
TheLeader, and if the code dont't generate an error, it just ignore the on E: Exception do ....

alsantos
0
 
TheLeaderAuthor Commented:
Well, Thank "alsantos"
you really deserve A :)
here you go...
0
 
alsantosCommented:
Thanks TheLeader :)

alsantos
0
 
NarusegawaCommented:
Hi, I've just tried your code above but it just locks up. Would it be possible to send me the code also, as this is a perfect example of a simple client-server I want to study.

Thanks... naru@eclipticdreams.com
0
 
masterchowCommented:
hi i tried to start the server with button1, but nothing happend.
procedure TForm1.Button1Click(Sender: TObject);
begin
  try
    IdTcpServer1.DefaultPort:=StrToInt(Edit1.Text);
    IdTCPServer1.Active := true;
    ListBox1.Items.Append('Server started')

  except on E : Exception do
      ListBox1.Items.Append('Server not started');
  end;
end;

could u also send me the source code..? nhatiboy@hotmail.com
thanx in advance
0
 
mehdi_mCommented:
masterchow you can use IdTcpServer1.Bindings property in design mode to simply set the HostIP and Port like:     127.0.0.1:80
0
 
emu10k1Commented:
alsantos cannot help you anymore, the community moderators close their account.
0
 
vhisnusanCommented:
my app use ado to handle database, and i try to use seek method, but it says "provider doesn't support this method" (index and seek method). can master help me to solve my BIG problem ...
^(~,~)^
0
 
EilisCommented:
I have to write a network management program in Delphi for monitoring switches and discovering when a switch fails. It should retrieve the status of the monitored device from its MIB file.
Could you provide me with any tips on how to design this. I have never programmed in Delphi before and am a complete newbie. But I understand all about network management.
The information will be sent to a Server every X seconds and any changes should be sent to the monitored devices, such as traps. I would be very grateful.
Thanks
Eilis
0
 
mahfudCommented:
Dear TheLeader,

Can you send me the source code from alsantos about indy client server, caused of alsantos account has been closed. My email japriku2000@yahoo.com

Thanks
0
 
DragomirIvanovCommented:
Dear TheLeader
Can u send me a compiled program to email : drago666@abv.bg
 Thanks
0
 
dunglqCommented:
Dear TheLeader,
 Could you send me the source code to email: dunglq78@gmail.com

thanks alot
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now