WebSocketClientChannel.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using WebSocketSharp;
  5. using WebSocketSharp.Frame;
  6. namespace Taobao.Top.Link.Channel.WebSocket
  7. {
  8. /// <summary>websocket clientchannel via websocket-sharp impl
  9. /// </summary>
  10. public class WebSocketClientChannel : IClientChannel
  11. {
  12. private WebSocketSharp.WebSocket _socket;
  13. private ResetableTimer _timer;
  14. private EventHandler<ChannelContext> _onMessage;
  15. private EventHandler<ChannelContext> _onError;
  16. private EventHandler<ChannelClosedEventArgs> _onClosed;
  17. public EventHandler<ChannelContext> OnMessage
  18. {
  19. get { this.DelayPing(); return this._onMessage; }
  20. set { this._onMessage = value; }
  21. }
  22. public EventHandler<ChannelContext> OnError
  23. {
  24. get { this.DelayPing(); return this._onError; }
  25. set { this._onError = value; }
  26. }
  27. public EventHandler<ChannelClosedEventArgs> OnClosed
  28. {
  29. get { return this._onClosed; }
  30. set { this._onClosed = value; }
  31. }
  32. public Uri Uri { get; set; }
  33. public bool IsConnected { get { return this._socket.ReadyState == WsState.OPEN; } }
  34. public WebSocketClientChannel(WebSocketSharp.WebSocket socket)
  35. {
  36. this._socket = socket;
  37. this._onClosed += (o, e) =>
  38. {
  39. this.Close(e.Reason);
  40. };
  41. }
  42. public void Send(byte[] data)
  43. {
  44. this.CheckChannel();
  45. this._socket.Send(data);
  46. }
  47. public void Close(string reason)
  48. {
  49. this._socket.Close(CloseStatusCode.NORMAL, reason);
  50. if (this._timer != null)
  51. {
  52. this._timer.Cancel();
  53. this._timer = null;
  54. #if DEBUG
  55. Console.WriteLine("TMC: Info@close: " + reason);
  56. #endif
  57. }
  58. }
  59. public ResetableTimer HeartbeatTimer
  60. {
  61. set
  62. {
  63. this._timer = value;
  64. this._timer.Elapsed += (s, e) =>
  65. {
  66. if (this.IsConnected)
  67. //websocket-sharp's ping is sync
  68. this._socket.Ping();
  69. };
  70. }
  71. }
  72. private void CheckChannel()
  73. {
  74. if (!this.IsConnected)
  75. {
  76. if (this._timer != null)
  77. this._timer.Cancel();
  78. throw new LinkException("websocket channel closed");
  79. }
  80. this.DelayPing();
  81. }
  82. private void DelayPing()
  83. {
  84. try
  85. {
  86. if (this._timer != null)
  87. this._timer.Delay();
  88. }
  89. catch (Exception)
  90. {
  91. }
  92. }
  93. }
  94. }