TcpHandler.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Net.Sockets;
  5. using System.Threading;
  6. namespace LJLib.TcpHandle
  7. {
  8. internal abstract class TcpHandler
  9. {
  10. public TcpHandler(TcpClient client)
  11. {
  12. _client = client;
  13. _ns = _client.GetStream();
  14. _reader = new BinaryReader(_ns);
  15. _writer = new BinaryWriter(_ns);
  16. }
  17. protected TcpClient _client = null;
  18. protected NetworkStream _ns = null;
  19. protected BinaryReader _reader = null;
  20. protected BinaryWriter _writer = null;
  21. private bool _is_server = true;
  22. public TcpClient SetAsClient()
  23. {
  24. if (!_is_server)
  25. {
  26. throw new Exception("当前连接已经退出服务模式");
  27. }
  28. _is_server = false;
  29. return _client;
  30. }
  31. public void Handle()
  32. {
  33. var dt = DateTime.Now;
  34. // 客户端响应
  35. try
  36. {
  37. while (_is_server)
  38. {
  39. if (!_client.Connected)
  40. {
  41. return;
  42. }
  43. if (_ns.DataAvailable)
  44. {
  45. dt = DateTime.Now;
  46. DataArrived();
  47. dt = DateTime.Now;
  48. }
  49. else
  50. {
  51. if (_client.Client.Poll(1000, SelectMode.SelectRead) && !_ns.DataAvailable)
  52. {
  53. return;
  54. }
  55. // 3分钟无数据接收则断开连接
  56. if (DateTime.Now > dt.AddSeconds(180))
  57. {
  58. Trace.Write(string.Format("3分钟无数据接收则断开连接:{0}秒", (DateTime.Now - dt).TotalSeconds));
  59. return;
  60. }
  61. Thread.Sleep(100);
  62. }
  63. }
  64. }
  65. catch (Exception ex)
  66. {
  67. Trace.Write(string.Format("用时:{0}秒,异常:{1}", (DateTime.Now - dt).TotalSeconds, ex.ToString()));
  68. }
  69. finally
  70. {
  71. if (_is_server)
  72. {
  73. Thread.Sleep(1000);
  74. using (_client)
  75. using (_ns)
  76. using (_reader)
  77. using (_writer)
  78. {
  79. }
  80. OnClosed();
  81. }
  82. }
  83. }
  84. protected abstract void DataArrived();
  85. protected virtual void OnClosed() { }
  86. }
  87. }