簡體   English   中英

C#TCP套接字Keepalive

[英]C# tcp socket keepalive

我正在用C#創建一個客戶端應用程序,以通過telnet協議將命令發送到遠程路由器。 當前,遠程路由器關閉空閑連接2到5分鍾。 我正在尋找一種保持聯系的方式。 我嘗試了以下代碼:

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

但這不起作用。

這是我的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);
        }
    }
}

在我團隊的一種產品中,我們發現TCP保持活動間隔的觸發頻率不足以使某些NAT的路由器端口保持打開狀態。

我們更新了協議,以發送“ ping”消息,每45秒以“ pong”響應。 但這是針對我們控制的協議。

對於telnet,最好的選擇是在每個間隔上發送telnet轉義字符,后跟NOP(241)或AYT(246)的telnet命令。 有關更多詳細信息,請參見RFC 854。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM