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

uses
  SysUtils,
  Windows,
  WinSock;

type
  bytearray = array of byte;

procedure string2bytearray(s : string; var b : bytearray);

var
  i : integer;

begin
  SetLength(b, Length(s));
  for i := 1 to Length(s) do b[Low(b) + i -1] := ord(s[i]);
end;

function RecvLine(s : TSocket) : string;

var
  res : string;
  buf : bytearray;
  ix : integer;

begin
  SetLength(buf, 256);
  ix := 0;
  while (ix < Length(buf)) and ((buf[ix - 2] <> 13) or (buf[ix - 1] <> 10)) do begin
    ix := ix + Recv(s, buf[ix], Length(buf) - ix, 0);
  end;
  SetString(res, PAnsiChar(@buf[Low(buf)]), ix - 2);
  RecvLine := res;
end;

const
  PORT = 12345;
  BACKLOG = 100;

var
  wsa : TWSAData;
  s, s2 : TSocket;
  local, remote : TSockAddrIn;
  line, v, v2 : string;
  status, slen, a, b, c, ix : integer;
  buf : array of 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 *)
    line := RecvLine(s2);
    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;
    string2bytearray(IntToStr(c) + #13#10, buf);
    status := Send(s2, buf[Low(buf)], Length(buf), 0);
    if status < 0 then begin
      writeln('Error sending c: ' + SysErrorMessage(GetLastError));
      halt;
    end;
    (* read v *)
    v := RecvLine(s2);
    (* calculate v2 and send *)
    v2 := v + v;
    string2bytearray(v2 + #13#10, buf);
    status := Send(s2, buf[Low(buf)], Length(buf), 0);
    if status < 0 then begin
      writeln('Error sending v2: ' + SysErrorMessage(GetLastError));
      halt;
    end;
    CloseSocket(s2);
  end;
  CloseSocket(s);
  WSACleanup;
end.

