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

uses
  SysUtils,
  Windows,
  WinSock;

const
  HOST = 'localhost';
  PORT = 12345;

var
  wsa : TWSAData;
  s : TSocket;
  hostinfo : PHOstEnt;
  remote : TSockAddrIn;
  v, v2 : string;
  status, 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;
  (* 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;
  tmp := htonl(a);
  status := Send(s, @tmp, sizeof(tmp), 0);
  if status < 0 then begin
    writeln('Error sending a: ' + SysErrorMessage(GetLastError));
    halt;
  end;
  tmp := htonl(b);
  status := Send(s, @tmp, sizeof(tmp), 0);
  if status < 0 then begin
    writeln('Error sending b: ' + SysErrorMessage(GetLastError));
    halt;
  end;
  (* receive c and print *)
  buflen := sizeof(tmp);
  ix := 0;
  while ix < buflen do begin
    ix := ix + Recv(s, PChar(@tmp) + ix, buflen - ix, 0);
  end;
  c := ntohl(tmp);
  writeln(c);
  (* send v *)
  v := 'ABC';
  len := Length(v);
  status := Send(s, len, sizeof(len), 0);
  if status < 0 then begin
    writeln('Error sending v: ' + SysErrorMessage(GetLastError));
    halt;
  end;
  status := Send(s, v[1], len, 0);
  if status < 0 then begin
    writeln('Error sending v: ' + SysErrorMessage(GetLastError));
    halt;
  end;
  (* receive v2 and print *)
  Recv(s, @len, sizeof(len), 0);
  SetLength(buf, len);
  buflen := len;
  ix := 0;
  while ix < buflen do begin
    ix := ix + Recv(s, buf[Low(buf) + ix], buflen - ix, 0);
  end;
  SetString(v2, PAnsiChar(@buf[Low(buf)]), len);
  writeln(v2);
  CloseSocket(s);
  WSACleanup;
end.

