PageRenderTime 57ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/source/samples/ObviousCode.Interlace.BitTunnel/ObviousCode.Interlace.BitTunnelLibrary/Messages/Protocols/BitTunnelProtocolFactory.cs

https://bitbucket.org/VahidN/interlace
C# | 98 lines | 75 code | 23 blank | 0 comment | 6 complexity | f3b1e94b059a9b989299220db0491545 MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using Interlace.ReactorCore;
  4. using ObviousCode.Interlace.BitTunnelLibrary.Events;
  5. using ObviousCode.Interlace.BitTunnelLibrary.Interfaces;
  6. namespace ObviousCode.Interlace.BitTunnelLibrary.Protocols
  7. {
  8. public abstract class BitTunnelProtocolFactory : IProtocolFactory
  9. {
  10. List<BitTunnelProtocol> _protocols;
  11. public event EventHandler<ExceptionEventArgs> LostConnection;
  12. public event EventHandler<MessageEventArgs> MessageReceived;
  13. public event EventHandler<MessageEventArgs> MessageSending;
  14. AppSettings _settings;
  15. public BitTunnelProtocolFactory(AppSettings settings)
  16. {
  17. _protocols = new List<BitTunnelProtocol>();
  18. _settings = settings;
  19. }
  20. #region IProtocolFactory Members
  21. public Protocol BuildProtocol()
  22. {
  23. BitTunnelProtocol protocol = CreateProtocol();
  24. _protocols.Add(protocol);
  25. protocol.MessageReceived += new EventHandler<MessageEventArgs>(_protocol_MessageReceived);
  26. protocol.MessageSending += new EventHandler<MessageEventArgs>(protocol_MessageSending);
  27. return protocol;
  28. }
  29. void protocol_MessageSending(object sender, MessageEventArgs e)
  30. {
  31. if (MessageSending != null)
  32. {
  33. MessageSending(sender, e);
  34. }
  35. }
  36. public void ConnectionFailed(Exception ex)
  37. {
  38. OnConnectionFailed(ex);
  39. if (LostConnection != null)
  40. {
  41. LostConnection(this, new ExceptionEventArgs(ex));
  42. }
  43. }
  44. protected abstract BitTunnelProtocol CreateProtocol();
  45. public virtual void StartedConnecting()
  46. {
  47. }
  48. public abstract void OnConnectionFailed(Exception e);
  49. public abstract void OnMessageReceived(IMessage message);
  50. void _protocol_MessageReceived(object sender, MessageEventArgs e)
  51. {
  52. OnMessageReceived(e.Message);
  53. if (MessageReceived != null)
  54. {
  55. MessageReceived(sender, e);
  56. }
  57. }
  58. #endregion
  59. protected List<BitTunnelProtocol> ProtocolList
  60. {
  61. get { return _protocols; }
  62. }
  63. protected AppSettings Settings
  64. {
  65. get { return _settings; }
  66. }
  67. public void LoseConnection()//set this to internal then mark BitTunnel as an allowed assembly
  68. {
  69. foreach (BitTunnelProtocol protocol in ProtocolList)
  70. {
  71. protocol.LoseConnection();
  72. }
  73. }
  74. }
  75. }