Full source code now available on GitHub. Covering Internet Direct (Indy), Ararat Synapse, and Synapse SynCrtSock.
This is the first part in a series which explores basic TCP socket use cases and presents them in minimal examples, with useful comments regarding not-so-obvious requirements and pitfalls (a.k.a surprising results).
The clients are tested with a small console application (see below).
program FixedLengthClient;
uses
ClientMainIndy10,
SysUtils;
const
CONTENT_LENGTH = 8192;
SERVER_HOST = '127.0.0.1';
SERVER_PORT = 30000;
procedure Test(AExpectedLength: Integer);
var
Response: TBytes;
begin
WriteLn(Format('try to read %d bytes from %s:%d',
[AExpectedLength, SERVER_HOST, SERVER_PORT]));
Response := Read(SERVER_HOST, SERVER_PORT, AExpectedLength);
WriteLn(Format('received %d bytes', [Length(Response)]));
end;
begin
try
Test(CONTENT_LENGTH);
Test(CONTENT_LENGTH - 1);
Test(CONTENT_LENGTH + 1); // (surprise me)
except
on E: Exception do
begin
WriteLn(E.Message);
end;
end;
ReadLn;
end.
The first client uses Internet Direct (Indy). Here is the source code:
(*
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*)
unit ClientMainIndy10;
interface
uses
SysUtils;
function Read(AHost: string; APort: Integer; ALength: Integer): TBytes;
implementation
uses
IdTcpClient, IdGlobal, Classes;
function Read(AHost: string; APort: Integer; ALength: Integer): TBytes;
var
Client: TIdTCPClient;
begin
SetLength(Result, ALength);
Client := TIdTCPClient.Create;
try
Client.Host := AHost;
Client.Port := APort;
Client.Connect;
Client.IOHandler.ReadBytes(Result, Length(Result), False);
finally
Client.Free;
end;
end;
end.
Notes
- Included is a test server which responds wiith a fixed-length byte array. The test server requires Indy for compilation.
- Credits: partially inspired by the thread https://en.delphipraxis.net/topic/7935-dl-a-file-from-the-web/
- Fork me on GitHub: https://github.com/michaelJustin/tcpclient-test