欢迎您的来访!有源码,好建站(www.codehy.com)源码海洋源码网为您提供快速建站平台.
当前位置: 首页 > 行业资讯 > c# .net 资料 >

C# 实现客户端Socket断开后重新连接

时间:2021-07-11 23:00来源:未知 作者:admin 点击:
思路:使用System.Threading.Timer类每秒检测一次是否连接,如果没有处于连接状态,则尝试连接一次,如果连接失败,则将异常信息捕捉,并记录日志,然后Sleep2秒,再尝试连接,一直重复连接的步骤。 System.Threading.Timer timer = null; private void BtnC

 思路:使用System.Threading.Timer类每秒检测一次是否连接,如果没有处于连接状态,则尝试连接一次,如果连接失败,则将异常信息捕捉,并记录日志,然后Sleep2秒,再尝试连接,一直重复连接的步骤。

System.Threading.Timer timer = null;

 private void BtnConnect_Click(object sender, RoutedEventArgs e)

 {

            

            timer = new Timer(new TimerCallback(TimerCall),null,Timeout.Infinite,1000);

            timer.Change(0, 1000);

  }

 private void TimerCall(object obj)

 {

            if (!IsSocketConnected(socketWatch))

            { 

                    this.Dispatcher.Invoke(new Action(() =>

                    {

                        string connectIP = txtIP.Text;

                        string port = txtPort.Text;

 

                    try

                    {

                        socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                        IPAddress address = IPAddress.Parse(connectIP);

                        socketWatch.Connect(address, int.Parse(port));

                        threadWatch = new Thread(RecMsg);

                        threadWatch.IsBackground = true;

                        threadWatch.Start();

                        }

                        catch

                        { Thread.Sleep(2000); }

                    }));

               

            }

        }

        private bool IsSocketConnected(Socket socket)

        {

            lock (this)

            {

                bool ConnectState = true;

                bool state = socket.Blocking;

                try

                {

                    byte[] temp = new byte[1];

                    socket.Blocking = false;

                    socket.Send(temp, 0, 0);

                    ConnectState = true;

                }

                catch (SocketException e)

                {

                    if (e.NativeErrorCode.Equals(10035)) //仍然是connect的

                        ConnectState = true;

                    else

                        ConnectState = false;

                }

                finally

                {

                    socket.Blocking = state;

                }

                return ConnectState;

            }

}

 

(责任编辑:admin)本文地址:http://www.codehy.com/info/net/2021/0711/22467.html

推荐资讯