unit main;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, WSocketS, StdCtrls, ExtCtrls;

const HEADER = #$FF#$FF#$FF#$FF;
      LF = #$0A;
      CR = #$0D;

type
  TMainForm = class(TForm)
    ButtonCVARList: TButton;
    LabeledEditHost: TLabeledEdit;
    LabeledEditRConPassword: TLabeledEdit;
    MemoResponse: TMemo;
    ButtonGetStatus: TButton;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure ButtonCVARListClick(Sender: TObject);
    procedure ButtonGetStatusClick(Sender: TObject);
  private
   fUDPClient: TWSocketClient;
   fRxBuffer: string;

   procedure OnUDPDataAvailable(Sender: TObject; Error: word);
  public
    { Public declarations }
  end;

var
  MainForm: TMainForm;

implementation

{$R *.dfm}

procedure TMainForm.ButtonCVARListClick(Sender: TObject);
begin
 fRxBuffer := '';

 // close the UDP client in case host changed
 fUDPClient.Close();
 fUDPClient.Addr := LabeledEditHost.Text;
 fUDPClient.Port := '27960';
 fUDPClient.Connect();

 fUDPClient.SendStr(Format('%srcon %s %s %s', [HEADER, LabeledEditRConPassword.Text, 'cvarlist', LF]));
end;

procedure TMainForm.ButtonGetStatusClick(Sender: TObject);
begin
 fRxBuffer := '';

 // close the UDP client in case host changed

 fUDPClient.Close();
 fUDPClient.Addr := LabeledEditHost.Text;
 fUDPClient.Port := '27960';
 fUDPClient.Connect();

 fUDPClient.SendStr(Format('%s%s %s', [HEADER, 'getstatus', LF]));
end;

procedure TMainForm.FormCreate(Sender: TObject);
begin
 fUDPClient := TWSocketClient.Create(Self);
 fUDPClient.Proto := 'udp';
 fUDPClient.OnDataAvailable := OnUDPDataAvailable;
end;

procedure TMainForm.FormDestroy(Sender: TObject);
begin
 fUDPClient.Close();
end;

procedure TMainForm.OnUDPDataAvailable(Sender: TObject; Error: word);
var s: string;
begin
   s:= fUDPClient.ReceiveStr();        
 fRxBuffer := fRxBuffer + s;

 if fRxBuffer[Length(fRxBuffer)] = #$0A then
 begin
  // replace LF with CR + LF to make it more readable in the TMemo
  MemoResponse.Text := StringReplace(fRxBuffer, LF, CR + LF, [rfReplaceAll]);
  fRxBuffer := '';
 end;
end;

end.
