简体   繁体   中英

C# tcp socket keepalive

I am creating a client application in C# for sending commands via telnet protocol to a remote router. Currently the remote router closes idle connections for 2~5 minutes. I am looking for a way to keep alive my connection. I have tried following code:

socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

but it doesn't work.

Here is my code for TelnetClient:

public class TelnetClient
{
    private NetworkStream ns;
    private Socket client;
    private const string prompt = ">";
    private const int buffer = 2048;
    private string host;
    private int port;
    private string user;
    private string password;

    public TelnetClient(string host, int port, string user, string password)
    {
        client = new Socket(SocketType.Stream, ProtocolType.Tcp);

        client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
        this.host = host;
        this.port = port;
        this.user = user;
        this.password = password;
    }


    public bool Connect()
    {
        try
        {
            client.Connect(host, port); 
            ns = new NetworkStream(client);

            return true;
        }
        catch (Exception e)
        {
            Trace.TraceError(e.Message);

            return false;
        }
    }

    public bool Login()
    {
        Write(this.user);
        ReadUntil(":", 1000);
        Write(this.password);
        if(ReadUntil(">", 1000) != null)
            return true;
        return false;
    }

    public string ReadUntil(string pattern, long timeout)
    {
        StringBuilder sb = new StringBuilder();
        string text = "";
        byte[] arr = new byte[buffer];

        try
        {
            if (ns.CanRead)
            {
                Stopwatch s = new Stopwatch();
                s.Start();
                while (s.Elapsed < TimeSpan.FromMilliseconds(timeout))
                {
                    text = sb.ToString().Trim().ToLower();

                    if (pattern.Length > 0 && text.ToLower().Trim().EndsWith(pattern))
                    {
                        return text.ToLower();
                    }

                    if (ns.DataAvailable)
                    {
                        int count = ns.Read(arr, 0, arr.Length);
                        sb.AppendFormat("{0}", Encoding.ASCII.GetString(arr, 0, count));
                    }
                }
            }
            else
                return null;
        }
        catch (Exception ex)
        {
            Trace.TraceError(ex.Message);
        }
        return null;
    }

    public void Write(string value)
    {
        byte[] arr = Encoding.ASCII.GetBytes(value + Environment.NewLine);



        try
        {
            ns.Write(arr, 0, arr.Length);
            ns.Flush();
            System.Threading.Thread.Sleep(1000);
        }
        catch (Exception e)
        {
            Trace.TraceError(e.Message);
        }
    }

    public string SendCommand(string cmd, int timeout)
    {
        Write(cmd);
        return ReadUntil(prompt, timeout);
    }

    public void Disconnect()
    {
        try
        {
            byte[] arr = Encoding.ASCII.GetBytes("exit" + Environment.NewLine);
            ns.Write(arr, 0, arr.Length);
            ns.Close();
            client.Close();
        }
        catch (Exception e)
        {
            Trace.TraceError(e.Message);
        }
    }
}

On one of my team's products, we found that the TCP keep-alive interval wasn't fired sufficiently often enough to keep the router port open for certain NATs.

We updated the protocol to send a "ping" message that was responded with a "pong" every 45 seconds. But that was for a protocol that we controlled.

For telnet, best bet would be to send the telnet escape character followed by a telnet command of NOP (241) or AYT (246) on every interval. See RFC 854 for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM