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