How to make TCP/IP connection between Client and Server in Delphi?

How to make TCP/IP connection between Client and Server in Delphi?

This article demonstrates a code snippet showing you how to make TCP/IP connection between Clent and Server in Delphi? We will use Indy Component to make  TCP/IP connection between Clent and Server. We are going to use two TidTCPClient Class of Indy Components.

Server Side coding:

Setup TidTCPClient:

IdTCPServer1.Bindings.Clear;
IdTCPServer1.Bindings.Add.SetBinding('127.0.0.1', 8080);
IdTCPServer1.Active := True;

This tells the server to listen on the loopback address only, at port 8080. This prevents anyone outside of your computer from connecting to it.

Put following code in your TIdTCPServer component's OnExecute event:

var
  sResponse: string;
begin
  //Send "Hello" message to client immediately after connection
  AContext.Connection.Socket.WriteLn('Hello');
  //Receive "Hi" response from client
  sResponse:= AContext.Connection.Socket.ReadLn;
 //Disconnect
 AContext.Connection.Disconnect;
end;

Client Side coding

Suppose you have a delphi form and a button on it. By pressing the button, you make tcp/ip connection to the server.

procedure TForm1.Button1Click(Sender: TObject);
var
  sMsg : string;
begin
  try
    IdTCPClient1.Port  := xxxx; //Set port to connect to
    IdTCPClient1.Host := 'xxx.xxx.xxx.xxx'; //Set host to connect to
    IdTCPClient1.Connect; //Make tcp ip connection
    sMsg := IdTCPClient1.Socket.ReadLn; //Read the Hello message from the server
    ShowMessage(sMsg); //Show the message
    IdTCPClient1.Socket.WriteLn('Hi'); //Ping server with Hi message
  except
    on E : Exception do
    begin
      ShowMessage('Connection Error: ' + E.Message);
      exit;
    end;
  end;
end;

Explanation: You have to set port number and host IP address first. Then just connect to it. A TCP/IP connection will be established between Client and Sever. If you get connected successfully, you will get 'Hello' from server. Then you will send "Hi" to the server.