how to use vtnetcore in a commandline app

in #programming4 years ago

this is an expanded explaination to the issue here https://github.com/darrenstarr/VtNetCore/issues/7

The basic idea i chose was to make it parse away all the vt escape sequences and output a final string to the console.
the telnet part came from here https://github.com/blakepell/AvalonMudClient/blob/master/src/Avalon.Client/Network/TelnetClient.cs

using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using VtNetCore.VirtualTerminal;
using VtNetCore.XTermParser;

namespace VtNetCoreTest
{
    internal class Program
    {
        private static CancellationTokenSource ctc;
        private static TelnetClient telnetcli;
        private static VirtualTerminalController vtController;
        static DataConsumer DataPart;
        
        public static async Task Main(string[] args)
        {
           //towel blinken lights is well my favorite testing method
            await setupConnection("towel.blinkenlights.nl",23);
            await telnetcli.Connect();
            await telnetcli.Send("a");
           await WaitForItToWork();
        }
        //this loop is needed because vtnetcore doesnt expose an event handler where you can get the result string
        //think of it like animation frame updates
       static async Task WaitForItToWork()
        {
            while (true)
            {
                Console.Clear();
                Console.Write(vtController.GetScreenText());
                await Task.Delay(1000); // arbitrary delay to avoid excessive console flickering
            }
        }
        public static async Task setupConnection(string host, int port)
        {
            ctc = new CancellationTokenSource();
            //initalize the controller first
            vtController = new VirtualTerminalController();
            setup the size of the virtual terminal (this is actually important because without it nothing is written to the console window)
            vtController.ResizeView(80, 25);
            //the dataconsumer is is another important part without it you cant send raw data to the virtual terminal
            DataPart = new VtNetCore.XTermParser.DataConsumer(vtController);
            //initalize the telnet client but dont connect yet
            telnetcli = new TelnetClient(host, port, TimeSpan.FromSeconds(0), ctc.Token);
           //when data is recieved by the client pass it to the virtual terminal
            telnetcli.DataReceived += (sender, s) => DataPart.Push(Encoding.ASCII.GetBytes(s));

            vtController.SendData += (sender, args) => Console.WriteLine(args.Data);

        }
    }
}
Sort:  

this is how the output looks in rider