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

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
  HOST = 'localhost';
  PORT = 12345;

var
  wsa : TWSAData;
  s : TSocket;
  hostinfo : PHOstEnt;
  remote : TSockAddrIn;
  v, v2 : string;
  status, a, b, c : 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;
  (* connect to host *)
  hostinfo := GetHostByName(HOST);
  remote.sin_family := AF_INET;
  remote.sin_port :=  htons(PORT);
  remote.sin_addr.S_addr := PInAddr(hostinfo^.H_Addr_List^)^.S_addr;
  status := Connect(s, remote, sizeof(remote));
  if status <> 0 then begin
    writeln('Error connecting to host ' + HOST + ' port ' + IntToStr(PORT) + ': ' + SysErrorMessage(GetLastError));
    halt;
  end;
  (* send a and b *)
  a := 123;
  b := 456;
  string2bytearray(IntToStr(a) + ' ' + IntToStr(b) + #13#10, buf);
  status := Send(s, buf[Low(buf)], Length(buf), 0);
  if status < 0 then begin
    writeln('Error sending a and b: ' + SysErrorMessage(GetLastError));
    halt;
  end;
  (* receive c and print *)
  c := StrToInt(RecvLine(s));
  writeln(c);
  (* send v *)
  v := 'ABC';
  string2bytearray(v + #13#10, buf);
  status := Send(s, buf[Low(buf)], Length(buf), 0);
  if status < 0 then begin
    writeln('Error sending v: ' + SysErrorMessage(GetLastError));
    halt;
  end;
  (* receive v2 and print *)
  v2 := RecvLine(s);
  writeln(v2);
  CloseSocket(s);
  WSACleanup;
end.

