SocketToken.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. using System.Net;
  2. using System;
  3. using System.Net.Sockets;
  4. namespace IFramework.Net
  5. {
  6. public class SocketToken : IDisposable, IComparable<SocketToken>
  7. {
  8. /// <summary>
  9. /// 会话编号
  10. /// </summary>
  11. public int TokenId { get; set; }
  12. /// <summary>
  13. /// 会话socket对象
  14. /// </summary>
  15. public Socket TokenSocket { get; set; }
  16. /// <summary>
  17. /// 会话的终结点
  18. /// </summary>
  19. public IPEndPoint TokenIpEndPoint { get; set; }
  20. internal SocketAsyncEventArgs TokenAgrs { get; set; }
  21. private bool _isDisposed = false;
  22. //析构
  23. ~SocketToken()
  24. {
  25. Dispose(false);
  26. }
  27. /// <summary>
  28. /// 构造
  29. /// </summary>
  30. public SocketToken(int id)
  31. {
  32. this.TokenId = id;
  33. }
  34. public SocketToken() { }
  35. /// <summary>
  36. /// 关闭该连接对象,释放相关资源,非完全释放Socket对象
  37. /// </summary>
  38. public void Close()
  39. {
  40. if (TokenSocket != null)
  41. {
  42. try
  43. {
  44. TokenSocket.Shutdown(SocketShutdown.Send);
  45. }
  46. catch (ObjectDisposedException)
  47. { return; }
  48. catch { }
  49. TokenSocket.Close();
  50. }
  51. }
  52. /// <summary>
  53. /// 关闭该连接对象并释放该对象资源
  54. /// </summary>
  55. public void Dispose()
  56. {
  57. Dispose(true);
  58. GC.SuppressFinalize(this);
  59. }
  60. public bool SendAsync(SocketAsyncEventArgs args)
  61. {
  62. return TokenSocket.SendAsync(args);
  63. }
  64. public bool DisconnectAsync(SocketAsyncEventArgs args)
  65. {
  66. if (TokenSocket.Connected == false) return false;
  67. return TokenSocket.DisconnectAsync(args);
  68. }
  69. /// <summary>
  70. /// 根据SocketId比较大小
  71. /// </summary>
  72. /// <param name="sToken"></param>
  73. /// <returns></returns>
  74. public int CompareTo(SocketToken sToken)
  75. {
  76. return this.TokenId.CompareTo(sToken.TokenId);
  77. }
  78. public int Send(SegmentOffset dataSegment)
  79. {
  80. return this.TokenSocket.Send(dataSegment.buffer,
  81. dataSegment.offset,
  82. dataSegment.size, 0);
  83. }
  84. /// <summary>
  85. /// 释放资源
  86. /// </summary>
  87. /// <param name="isDisposing"></param>
  88. protected virtual void Dispose(bool isDisposing)
  89. {
  90. if (_isDisposed) return;
  91. if (isDisposing)
  92. {
  93. TokenAgrs.Dispose();
  94. TokenSocket = null;
  95. _isDisposed = true;
  96. }
  97. }
  98. }
  99. }