(* Collection of code snippets by Arne Vajhøj *)
(* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) *)
program PlainBinSingleServerHigh;

uses
  IdTCPServer, IdContext;

const
  PORT = 12345;
  BACKLOG = 100;

type
  ClientHandler = class
    public
      procedure Run(ctx : TIdContext);
  end;

procedure ClientHandler.Run(ctx : TIdContext);

var
  v, v2 : string;
  a, b, c, len : integer;

begin
  writeln('(connection from ', ctx.Connection.Socket.Binding.PeerIP, ':', ctx.Connection.Socket.Binding.PeerPort, ')');
  (* read a and b *)
  a := ctx.Connection.Socket.ReadInt32(true);
  b := ctx.Connection.Socket.ReadInt32(true);
  (* calculate c and send *)
  c := a + b;
  ctx.Connection.Socket.Write(c, true);
  (* read v *)
  len := ctx.Connection.Socket.ReadByte;
  v :=  ctx.Connection.Socket.ReadString(len);
  (* calculate v2 and send *)
  v2 := v + v;
  ctx.Connection.Socket.Write(Byte(length(v2)));
  ctx.Connection.Socket.Write(v2);
  (* close connection *)
  ctx.Connection.Disconnect;
end;

var
  srv : TIdTCPServer;
  h : ClientHandler;

begin
  (* listen on port *)
  srv := TIdTCPServer.Create();
  srv.ListenQueue := BACKLOG;
  srv.Bindings.Add.Port := PORT;
  srv.StartListening;
  (* accept connection *)
  h := ClientHandler.Create;
  srv.OnExecute := @h.Run;
  srv.Active := true;
  readln;
  (* close connection *)
  srv.Free;
end.

