program TcpTest;

uses
  CoBase,
  CoEth01,
  CoIPv4,
  CoTCP,
  CoINET;


const

  Data   : array[0..10] of Char = 'KITV40'#13#10;


var

  Data2  : array[0..1{40000}] of Byte;

  Status : TCoStatus;
  Sock   : PCoDevice;

  Address : TTcpAddress;

  SvrSock : PCoDevice;

  DataIn : array[0..32767] of Char;

  RecvLen : Word;

  Idx     : Word;

  cbMemAvail : Longint;

begin

  X;

  cbMemAvail := MemAvail;

  for Idx := Low(Data2) to High(Data2) do
  begin
    Data2[ Idx ] := (Idx mod 23) + Ord('A');
  end;


  Status := NetOpenStack( 'ETH01', 'IOBASE=$300',
               'IPADDR="192.168.1.210"', '' );

  if Status <> CST_SUCCESS then
  begin
    WriteLn( 'NetOpenStack() failed: ', CoStatusToStr( Status ) );
    Exit;
  end;


  WriteLn( 'Net stack opened' );

  Status := NetOpenSocket( 'TCP', 'LPORT=5000', '', Sock );

  if Status <> CST_SUCCESS then
  begin
    WriteLn( 'NetOpenSocket() failed: ', CoStatusToStr( Status ) );
    NetCloseStack( '' );
    Exit;
  end;

  WriteLn( 'TCP socket created' );

  Status := Sock^.CoBind( nil, COF_PROPAGATE, nil );

  if Status <> CST_SUCCESS then
  begin
    WriteLn( 'CoBind() failed: ', Sock^.CoStatusToStr( Status ) );
    NetCloseSocket( Sock );
    NetCloseStack( '' );
    Exit;
  end;

  Status := Sock^.CoListen( 2, 0, nil );

  WriteLn( 'TCP socket bound' );

  Status := Sock^.CoAccept( @Address, SvrSock, nil, 0, nil );

  case Status of

    CST_SUCCESS:
    begin
      WriteLn( 'New socket created!:-)' );
    end;

  else
    WriteLn( 'CoAccept() failed: ', Sock^.CoStatusToStr( Status ) );

    Exit;
  end;


  repeat

    Status := SvrSock^.CoRecvBuffer( @DataIn, SizeOf( DataIn ), @RecvLen, 0, nil );

    if Status <> CST_SUCCESS then
    begin
      WriteLn( 'CoRecvBuffer() failed: ', CoStatusToStr( Status ) );
      Break;
    end
    else begin
      WriteLn( 'Received: ', RecvLen, ' bytes' );
    end;

  until False;


  Status := SvrSock^.CoDisconnect( 0, nil );

  Status := SvrSock^.CoUnbind( 0, nil );

  CoReleaseDevicePtr( SvrSock );

{  Status := Sock^.CoDisconnect( 0, nil );

  if Status <> CST_SUCCESS then
  begin
    WriteLn( 'CoDisconnect() failed: ', Sock^.CoStatusToStr( Status ) );
  end;}


  Status := Sock^.CoUnbind( COF_PROPAGATE, nil );

  if Status <> CST_SUCCESS then
  begin
    WriteLn( 'CoUnbind() failed: ', Sock^.CoStatusToStr( Status ) );
  end;


  NetCloseSocket( Sock );

  NetCloseStack( '' );

  WriteLn( 'MemAvail Diff: ', cbMemAvail - MemAvail );
end.