Pages

Sunday, 6 January 2013

How to Read Bytes in Socket Programming using Indy Client in Delphi XE2?

How to Read Bytes in Socket Programming using Indy Client in Delphi XE2?

Following is the delphi program which uses indy clients to read individual bytes from server in socket programming in delphi. I have created three delphi functions to connect, read bytes and then disconnect from server. Lets discuss them one by one.

Connect to Server using Indy Client: Use Indy Client to connect with server. Provide port number, IP address of the server to which you are going to connect. Have a look at very simple delphi program to connect to server in socket programming using delphi indy client.

procedure TForm1.ConnectToServer;
begin
  try
    if IdTCPClient1.Connected then
      exit
    else
    begin
      IdTCPClient1.Port  := 1234 //Port number
      IdTCPClient1.Host := '123.123.123.123'; //IP address of the server
      IdTCPClient1.Connect;
      if IdTCPClient1.Connected then  ShowMessage('Connected to Server');
    end;
  except
    on E : Exception do
    begin
      ShowMessage('Connection Error: ' + E.Message);
      exit;
    end;
  end;
end;

Read Bytes from Server using Indy Client: After getting connected to server, time to read bytes which have been placed by the server on the specific port. First of all check if the buffer is empty or not by using InputBufferIsEmpty function. If buffer is empty then check for data on source. I have passed 1000 as a parameter to the function CheckForDataOnSource so that client waits for 1 second to read data from port. I am assuming that server is writing 256 bytes of data on the port. I will use ReadBytes delphi function to read 256 bytes of data and store it into the TBytes Array. "True" argument denotes that each bytes read should get appended. Then I will go through the loop to show all the bytes read into the memo field.

procedure TForm1.ReadBytes;
var
  Buffer : TBytes;
  i : integer;
begin
  try
    if IdTCPClient1.IOHandler.InputBufferIsEmpty then
    begin
      if IdTCPClient1.IOHandler.CheckForDataOnSource(1000) then
      begin
         IdTCPClient1.IOHandler.ReadBytes(Buffer,256,true);
         Memo1.Clear;
         for i := 0 to 255 do
          Memo1.Lines.Add(IntToStr(buffer[i]));     
      else
        IdTCPClient1.IOHandler.InputBuffer.Clear;
    end
    else
      IdTCPClient1.IOHandler.InputBuffer.Clear;
  except
    on E : Exception do
    begin
      ShowMessage('Connection Error: ' + E.Message);
      exit;
    end;
  end;
end;

Disconnect from Server using Indy Client: After reading all the individual bytes, time to disconnect from the server and clear the input buffer.

function TForm1.DisconnectFromServer;
begin
  try
    IdTCPClient1.Disconnect;
    IdTCPClient1.IOHandler.InputBuffer.Clear;
  except
    on E : Exception do
    begin
      ShowMessage('Connection Error: ' + E.Message);
      exit;
    end;
  end;
end;

No comments:

Post a Comment