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

uses
  SysUtils,
  Windows,
  WinSock;

const
  PORT = 12345;
  BACKLOG = 100;

var
  wsa : TWSAData;
  s, s2 : TSocket;
  local, remote : TSockAddrIn;
  v, v2 : string;
  status, slen, a, b, c, tmp, ix, buflen : integer;
  buf : array of byte;
  len : byte;

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) + ')');
    (* 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);
  end;
  CloseSocket(s);
  WSACleanup;
end.

