Solved

Indy TCP (Client/Server)

Posted on 2003-10-26
24
51,662 Views
Last Modified: 2012-06-27
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
Comment
Question by:TheLeader
24 Comments
 
LVL 2

Expert Comment

by:alsantos
Comment Utility
I think that it's a lot of work to a few points.

alsantos :)
0
 
LVL 2

Author Comment

by:TheLeader
Comment Utility
I already Increased it, and if it a lot of works, theres no worry to increased it again ;)
0
 
LVL 3

Expert Comment

by:huferry
Comment Utility
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
 
LVL 12

Expert Comment

by:Lee_Nover
Comment Utility
how about checking the examples ?
basic Chat should be enough
0
 
LVL 2

Author Comment

by:TheLeader
Comment Utility
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
 
LVL 2

Accepted Solution

by:
alsantos earned 100 total points
Comment Utility
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
 
LVL 2

Expert Comment

by:alsantos
Comment Utility
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
 
LVL 2

Expert Comment

by:alsantos
Comment Utility
If you want, I can send the source code for your email.

alsantos
0
 
LVL 2

Author Comment

by:TheLeader
Comment Utility
yes I would like to
mido@ksaguys.com
0
 
LVL 2

Author Comment

by:TheLeader
Comment Utility
"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
 

Expert Comment

by:emu10k1
Comment Utility
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
 
LVL 2

Expert Comment

by:alsantos
Comment Utility
I wrote this comment at friend's house. But it's me.
alsantos :)
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 2

Expert Comment

by:alsantos
Comment Utility
TheLeader, and if the code dont't generate an error, it just ignore the on E: Exception do ....

alsantos
0
 
LVL 2

Author Comment

by:TheLeader
Comment Utility
Well, Thank "alsantos"
you really deserve A :)
here you go...
0
 
LVL 2

Expert Comment

by:alsantos
Comment Utility
Thanks TheLeader :)

alsantos
0
 

Expert Comment

by:Narusegawa
Comment Utility
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
 

Expert Comment

by:masterchow
Comment Utility
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
 

Expert Comment

by:mehdi_m
Comment Utility
masterchow you can use IdTcpServer1.Bindings property in design mode to simply set the HostIP and Port like:     127.0.0.1:80
0
 

Expert Comment

by:emu10k1
Comment Utility
alsantos cannot help you anymore, the community moderators close their account.
0
 

Expert Comment

by:vhisnusan
Comment Utility
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
 

Expert Comment

by:Eilis
Comment Utility
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
 

Expert Comment

by:mahfud
Comment Utility
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
 

Expert Comment

by:DragomirIvanov
Comment Utility
Dear TheLeader
Can u send me a compiled program to email : drago666@abv.bg
 Thanks
0
 

Expert Comment

by:dunglq
Comment Utility
Dear TheLeader,
 Could you send me the source code to email: dunglq78@gmail.com

thanks alot
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

This article explains how to create forms/units independent of other forms/units object names in a delphi project. Have you ever created a form for user input in a Delphi project and then had the need to have that same form in a other Delphi proj…
Objective: - This article will help user in how to convert their numeric value become words. How to use 1. You can copy this code in your Unit as function 2. than you can perform your function by type this code The Code   (CODE) The Im…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now