How to run async task in background?

8/14/2019

I need to forward the port of running service in k8s cluster. So I have use the example provided in github repo to do port forward for specific service. Now I would like to use the example in my test but when I call port forward method then I always get web socket exception but if I written the same code in console application then I don't get any exception it run perfectly fine.

private async Task<bool> ForwardPortOperation(string podName, int[] originalPort, int forwardPort)
        {
            var pod = GetPodObject(podName);

            var webSocket = await _config.GetK8SClient().WebSocketNamespacedPodPortForwardAsync(pod.Metadata.Name, pod.Metadata.NamespaceProperty, originalPort, WebSocketProtocol.V4BinaryWebsocketProtocol);

            var demux = new StreamDemuxer(webSocket);
            demux.Start();

            var stream = demux.GetStream((byte?)0, (byte?)0);

            IPAddress ipAddress = IPAddress.Loopback;
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, forwardPort);
            Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            listener.Bind(localEndPoint);
            listener.Listen(100);

            Socket handler = null;

            var accept = Task.Run(() =>
            {
                while (true)
                {
                    handler = listener.Accept();

                    var bytes = new byte[4096];
                    while (true)
                    {
                        int bytesRec = handler.Receive(bytes);
                        stream.Write(bytes, 0, bytesRec);
                        if (bytesRec == 0 || Encoding.Default.GetString(bytes, 0, bytesRec).IndexOf("<EOF>", StringComparison.InvariantCultureIgnoreCase) > -1)
                        {
                            break;
                        }
                        listener.Close();
                    }
                }
            });

            var copy = Task.Run(() =>
            {
                var buff = new byte[4096];
                while (true)
                {
                    var read = stream.Read(buff, 0, 4096);
                    handler.Send(buff, read, 0);
                }
            });

            await accept;
            await copy;

            return true;
        }

Port forward method:

public bool PortForward(string podName, int[] originalPort, int forwardPort)
        {
            return Task.Run(() => ForwardPortOperation(podName, originalPort, forwardPort)).Result;
        }

Nunit test project:

[Test]
 public void VerifyPortForward()
{
    new Pod(_config).PortForward("web_service_application", new int[3100], 1615);
}

How can I run such async method in background? so that once port forward successful then I can continue to another test.

Exception: https://gist.github.com/gittadesushil/bc3bf008b7a4fc62c33e97ab1fbf687f

-- Sushil Tade
c#
kubernetes
portforwarding
websocket

1 Answer

8/14/2019

I assume the method PortForward should be rewritten to be asynchronous in the following way:

public async Task<bool> PortForward(string podName, int[] originalPort, int forwardPort)
{
    return await Task.Run(() => ForwardPortOperation(podName, originalPort, forwardPort));
}

After that you can write a NUnit test:

[Test]
public async Task VerifyPortForward()
{
    var pod = new Pod(_config);
    var result = await pod.PortForward("web_service_application", new int[3100], 1615);
    // TODO: assert the result
}
-- Demid Dementev
Source: StackOverflow