program client;

uses Sockets, Linux;

const
 MyPort=9999;
 MaxClients=5;
 Err_TryAgain=11;
 Err_InProgress=115;

var 
 msg:string;
 rd,k:longint;

procedure Error(s:string);
 begin
  writeln('ERROR: ',s);
  halt;
 end;

function SwapWord(w:word):word;
 begin
  SwapWord:=(w shl 8) or (w shr 8);
 end;

var
 conn:longint;
 SA:TInetSockAddr;
 OK:boolean;

begin
 conn:=Socket(AF_INET,SOCK_STREAM,0 {PF_INET});
 if conn<0 then Error('socket');
 fcntl(conn,F_SetFl,Open_NonBlock);
 with SA do begin
  family:=AF_INET;
  port:=SwapWord(MyPort);
  addr:=((1 shl 24) or 127); { localhost }
 end;

 repeat
  OK:=Connect(conn,SA,SizeOf(SA));
  if (not OK) and 
     (SocketError=Err_InProgress) 
   then writeln('In progress ...');  
  if (not OK) and 
     ((SocketError<>Err_TryAgain) and
      (SocketError<>Err_InProgress)) 
   then begin
    writeln('LE=',LinuxError);
    writeln('SE=',SocketError);
    Error('connect');
   end; 
 until OK;

 writeln('New connection to server !!!');

 for k:=1 to 4 do begin
 repeat
  rd:=fdRead(conn,msg[1],1);
 until rd>0;
 msg[0]:=chr(rd);
 writeln('Input=[',msg,']');
 end;
 
 fdWrite(conn,msg[1],ord(msg[0]));
 
 shutdown(conn,2);
 fdclose(conn);
end.

