TcpSocket.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. 
  2. using System;
  3. using System.Net.Sockets;
  4. using System.Net;
  5. namespace IFramework.Net.Tcp
  6. {
  7. internal class TcpSocket
  8. {
  9. protected Socket socket = null;
  10. protected bool isConnected = false;
  11. protected EndPoint ipEndPoint = null;
  12. protected byte[] receiveBuffer = null;
  13. protected int receiveTimeout = 1000 * 60 * 30;
  14. protected int sendTimeout = 1000 * 60 * 30;
  15. protected int connectioTimeout = 1000 * 60 * 30;
  16. protected int receiveChunkSize = 4096;
  17. public TcpSocket(int size)
  18. {
  19. this.receiveChunkSize = size;
  20. receiveBuffer = new byte[size];
  21. }
  22. protected void CreateTcpSocket(int port,string ip)
  23. {
  24. ipEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
  25. Socket socket = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
  26. {
  27. LingerState = new LingerOption(true, 0),
  28. NoDelay = true,
  29. ReceiveTimeout = receiveTimeout,
  30. SendTimeout = sendTimeout
  31. };
  32. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  33. this.socket = socket;
  34. }
  35. protected void SafeClose()
  36. {
  37. if (socket == null) return;
  38. if (socket.Connected)
  39. {
  40. try
  41. {
  42. socket.Shutdown(SocketShutdown.Send);
  43. }
  44. catch (ObjectDisposedException)
  45. {
  46. return;
  47. }
  48. catch (Exception ex)
  49. {
  50. #if DEBUG
  51. Console.WriteLine(ex.TargetSite.Name + ex.Message);
  52. #endif
  53. }
  54. }
  55. try
  56. {
  57. socket.Close();
  58. }
  59. catch (Exception ex) {
  60. #if DEBUG
  61. Console.WriteLine(ex.TargetSite.Name + ex.Message);
  62. #endif
  63. }
  64. }
  65. protected void SafeClose(Socket s)
  66. {
  67. if (s == null) return;
  68. if (s.Connected)
  69. {
  70. try
  71. {
  72. s.Shutdown(SocketShutdown.Send);
  73. }
  74. catch (ObjectDisposedException ex)
  75. {
  76. #if DEBUG
  77. Console.WriteLine(ex.TargetSite.Name + ex.Message);
  78. #endif
  79. return;
  80. }
  81. catch (Exception ex)
  82. {
  83. #if DEBUG
  84. Console.WriteLine(ex.TargetSite.Name + ex.Message);
  85. #endif
  86. }
  87. }
  88. try
  89. {
  90. s.Close();
  91. //s.Dispose();
  92. s = null;
  93. }
  94. catch(Exception ex)
  95. {
  96. #if DEBUG
  97. Console.WriteLine(ex.TargetSite.Name + ex.Message);
  98. #endif
  99. }
  100. }
  101. }
  102. }