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

川长思鸟来 2022-10-29 07:35 639阅读 0赞

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

  1. System.Threading.Timer timer = null;
  2. private void BtnConnect_Click(object sender, RoutedEventArgs e)
  3. {
  4. timer = new Timer(new TimerCallback(TimerCall),null,Timeout.Infinite,1000);
  5. timer.Change(0, 1000);
  6. }
  7. private void TimerCall(object obj)
  8. {
  9. if (!IsSocketConnected(socketWatch))
  10. {
  11. this.Dispatcher.Invoke(new Action(() =>
  12. {
  13. string connectIP = txtIP.Text;
  14. string port = txtPort.Text;
  15. try
  16. {
  17. socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  18. IPAddress address = IPAddress.Parse(connectIP);
  19. socketWatch.Connect(address, int.Parse(port));
  20. threadWatch = new Thread(RecMsg);
  21. threadWatch.IsBackground = true;
  22. threadWatch.Start();
  23. }
  24. catch
  25. { Thread.Sleep(2000); }
  26. }));
  27. }
  28. }
  29. private bool IsSocketConnected(Socket socket)
  30. {
  31. lock (this)
  32. {
  33. bool ConnectState = true;
  34. bool state = socket.Blocking;
  35. try
  36. {
  37. byte[] temp = new byte[1];
  38. socket.Blocking = false;
  39. socket.Send(temp, 0, 0);
  40. ConnectState = true;
  41. }
  42. catch (SocketException e)
  43. {
  44. if (e.NativeErrorCode.Equals(10035)) //仍然是connect的
  45. ConnectState = true;
  46. else
  47. ConnectState = false;
  48. }
  49. finally
  50. {
  51. socket.Blocking = state;
  52. }
  53. return ConnectState;
  54. }
  55. }

发表评论

表情:
评论列表 (有 0 条评论,639人围观)

还没有评论,来说两句吧...

相关阅读