How to sustain TcpListener keep-alive?

I'm creating a https SSL listener that works on top of the tcplistener, but I'm having a problem with the TCP keep-alive.
The itself server works well, but it seems that every request cannot reuse previous connections.

The code below was trimmed to reduce the size of the example. Btw, I open the streams and discard them at the end of TCPListeners egiBeginAcceptTcpClient callback . I couldn't find another example or documentation about it, so idk if I should reuse networkstreams or just accept another tcpclient.

public class SecureProxy
{
    private TcpListener listener;
    private HttpClient proxyClient;

    public void Start()
    {
        listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
        listener.Server.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, 120);
        listener.Server.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, 10);
        listener.Server.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, 5);

        listener.Start();
        listener.BeginAcceptTcpClient(ReceiveClientAsync, null);
    }

    void ReceiveClientAsync(IAsyncResult ar)
    {
        var client = listener.EndAcceptTcpClient(ar);
        listener.BeginAcceptTcpClient(ReceiveClientAsync, null);

        using var ns = client.GetStream();
        using var sn = new SslStream(ns, true);

        try
        {
            sn.AuthenticateAsServer(ServerCertificate, ClientCertificateRequired, AllowedProtocols, CheckCertificateRevocation);
        }
        catch
        {
            return; // client refused the self signed cert
        }

        // read the https request and send a https response through sn
        sn.Flush();
    }
}


my question is: how i'm supposed to manage the tcplistener clients/streams in order to mantain keep-alive connections?
image.png
Was this page helpful?