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();
        }

 

posted @ 2021-12-13 08:37  txwtech  阅读(2831)  评论(0编辑  收藏  举报