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

uses
  IdTCPServer, IdContext, SysUtils;

const
  PORT = 12345;
  BACKLOG = 100;

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

procedure ClientHandler.Run(ctx : TIdContext);

var
  line, v, v2 : string;
  a, b, c, ix : integer;

begin
  writeln('(connection from ', ctx.Connection.Socket.Binding.PeerIP, ':', ctx.Connection.Socket.Binding.PeerPort, ')');
  (* read a and b *)
  line := ctx.Connection.Socket.ReadLn;
  ix := Pos(' ', line);
  a := StrToInt(Copy(line, 1, ix - 1));
  b := StrToInt(Copy(line, ix + 1, length(line) - ix));
  (* calculate c and send *)
  c := a + b;
  ctx.Connection.Socket.WriteLn(IntToStr(c));
  (* read v *)
  v :=  ctx.Connection.Socket.ReadLn;
  (* calculate v2 and send *)
  v2 := v + v;
  ctx.Connection.Socket.WriteLn(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.

