program TcpTest;

uses
  Crt,
  CoBase,
  CoEth01,
  CoIPv4,
  CoTCP,
  CoINET;


const

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


var

  Data2  : array[0..40000] of Byte;

  Status : TCoStatus;
  Sock   : PCoDevice;

  Address : TTcpAddress;

  SvrSock : PCoDevice;

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

  RecvLen : Word;

  Idx     : Word;

  T       : TCOTime;

begin


  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=23', '', 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;

  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 ) );
  end;



  for Idx := 0 to 10 do
  begin
    Status := Sock^.CoSendBuffer( @Data2, SizeOf( Data2 ), COF_TCP_PUSH, nil );
    if KeyPressed then Break;
  end;

  Status := Sock^.CoSendBuffer( @Data, SizeOf( Data ), COF_TCP_PUSH, nil );

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

  repeat

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

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

      Status := Sock^.CoSendBuffer( @DataIn, RecvLen, COF_TCP_PUSH, nil );
      if Status <> CST_SUCCESS then
      begin
        WriteLn( 'CoSendBuffer() failed: ', CoStatusToStr( Status ) );
      end;

    end;

  until KeyPressed;

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


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

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

  NetCloseSocket( Sock );

  NetCloseStack( '' );
end.