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

uses
  Classes,
  SysUtils,
  Windows,
  WinSock;

type
  ClientHandler = class(TThread)
    constructor Create(s2 : TSocket);
  protected
    procedure Execute; override;
  private
    _s2 : TSocket;
  end;

constructor ClientHandler.Create(s2 : TSocket);

begin
  inherited Create(false);
  _s2 := s2;
end;

procedure ClientHandler.Execute;

var
  v, v2 : string;
  status, a, b, c, tmp, ix, buflen : integer;
  buf : array of byte;
  len : byte;

begin
  (* read a and b *)
  buflen := sizeof(tmp);
  ix := 0;
  while ix < buflen do begin
    ix := ix + Recv(_s2, PChar(@tmp) + ix, buflen - ix, 0);
  end;
  a := ntohl(tmp);
  buflen := sizeof(tmp);
  ix := 0;
  while ix < buflen do begin
    ix := ix + Recv(_s2, PChar(@tmp) + ix, buflen - ix, 0);
  end;
  b := ntohl(tmp);
  (* calculate c and send *)
  c := a + b;
  tmp := htonl(c);
  status := Send(_s2, @tmp, sizeof(tmp), 0);
  if status < 0 then begin
    writeln('Error sending c: ' + SysErrorMessage(GetLastError));
    halt;
  end;
  (* read v *)
  Recv(_s2, @len, sizeof(len), 0);
  SetLength(buf, len);
  buflen := len;
  ix := 0;
  while ix < buflen do begin
    ix := ix + Recv(_s2, buf[Low(buf) + ix], buflen - ix, 0);
  end;
  SetString(v, PAnsiChar(@buf[Low(buf)]), len);
  (* calculate v2 and send *)
  v2 := v + v;
  len := Length(v2);
  status := Send(_s2, len, sizeof(len), 0);
  if status < 0 then begin
    writeln('Error sending v2: ' + SysErrorMessage(GetLastError));
    halt;
  end;
  status := Send(_s2, v2[1], len, 0);
  if status < 0 then begin
    writeln('Error sending v2: ' + SysErrorMessage(GetLastError));
    halt;
  end;
  CloseSocket(_s2);
  Self.Free;
end;

const
  PORT = 12345;
  BACKLOG = 100;

var
  wsa : TWSAData;
  s, s2 : TSocket;
  local, remote : TSockAddrIn;
  status, slen : integer;

begin
  WSAStartup($101, wsa);
  (* create socket *)
  s := Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  if s = INVALID_SOCKET then begin
     writeln('Error creating socket: ' + SysErrorMessage(GetLastError));
     halt;
  end;
  (* bind *)
  local.sin_family := AF_INET;
  local.sin_port :=  htons(PORT);
  local.sin_addr.S_addr := INADDR_ANY;
  status := bind(s, local, sizeof(local));
  if status <> 0 then begin
    writeln('Error binding socket: ' + SysErrorMessage(GetLastError));
    halt;
  end;
  (* listen *)
  status := listen(s, BACKLOG);
  if status <> 0 then begin
    writeln('Error listening socket: ' + SysErrorMessage(GetLastError));
    halt;
  end;
  while true do begin
    (* accept *)
    slen := sizeof(remote);
    s2 := Accept(s, @remote, slen);
    writeln('(connection from ' + inet_ntoa(remote.sin_addr) + ')');
    ClientHandler.Create(s2).Start;
  end;
  CloseSocket(s);
  WSACleanup;
end.

