program test; {$mode objfpc} {$H+}

uses sockets, sysutils, classes;



procedure perror (const s: string);
var e:integer;
begin
  // if cannot bind to port 80, should report 10048
  e:=SocketError;
  writeln ('ERROR: ', S, e);
end;

procedure socktest;
var
  S        : Longint;
  SAddr    : TInetSockAddr;
begin
  S:=Socket (AF_INET,SOCK_STREAM,0);
  if SocketError<>0 then Perror ('Socket : ');
  SAddr.sin_family:=AF_INET;
  { port 80 in network order }
  SAddr.sin_port:=htons(2000);
  SAddr.sin_addr.s_addr:=StrToNetAddr('1.2.3.4').s_addr;
  if not sockets.Connect(S,SAddr,sizeof(saddr)) then PError ('Connect : ') else Writeln('Connected!');
end;

type

{ TTestThread }

TTestThread = class(TThread)
public
 Finished:boolean;
 procedure execute;override;
end;

{ TTestThread }

procedure TTestThread.execute;
begin
  SockTest;
  Finished:=true;
end;


procedure threadtest;
var t:array[1..3] of TTestThread;
    i:integer;
    finito:boolean;
begin
  for i:=1 to 3 do
  begin
   T[i]:=TTestThread.Create(false);
   writeln('Thread ',i,' created');
   sleep(1000);
  end;
  finito:=false;
  while not finito do
  begin
    finito:=true;
    for i:=1 to 3 do finito:=finito and t[i].finished;
  end;
end;

begin
  writeln;
  writeln('Testing WSAGetLastError inside thread...');
  writeln;
  ThreadTest(); // comment this line out and you do get 10048 further below
end.
