天天看點

C# 實作用戶端Socket斷開後重新連接配接。

思路:使用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;
            }
}