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

uses
  Classes,
  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;

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
  line, v, v2 : string;
  status, a, b, c, ix : integer;
  buf : array of byte;

begin
  (* 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);
  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.

