c# Socket tcpClient處理連接超時方式timeout


Sockets里面的Connect連接方法,沒有對連接超時的處理,系統默認20-30秒,等待時間長。所有直接用timer來實現,沒有連接上,直接tcpclitnet.close來關閉掉。

using System.Net.Sockets;

public static Socket tcpClient;

可以用計時器timer來實現,

 

       public void Connect()
        {
            try
            {
                tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress iPAddress = IPAddress.Parse(IP);
                EndPoint endPoint = new IPEndPoint(iPAddress, port);
                RunFlag = false;
                // tcpClient.SendTimeout = 1000;

                timer.Interval = 1000;
                timer.Elapsed += MonitorTCP;


                if (!tcpClient.Connected)
                {


                    lock (Obj)
                    {
                        timer.Start();

                        tcpClient.Connect(endPoint);

                        RunFlag = true;

                        //  SendMsg("abc");
                    }
                }
            }
            catch
            {
                tcpClient.Close();
                RunFlag = false;
                RightReciver = "vision連接失敗\r\n檢查IP與端口配置";
                MessageBox.Show(RightReciver);

            }
        }

        public void MonitorTCP(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (!tcpClient.Connected)
            {
                tcpClient.Close();
            }
            //      tcpClient.Disconnect(true);
            timer.Stop();
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM