SocketListenerBase.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using SuperSocket.SocketBase;
  9. using SuperSocket.SocketBase.Config;
  10. namespace SuperSocket.SocketEngine
  11. {
  12. abstract class SocketListenerBase : ISocketListener
  13. {
  14. public ListenerInfo Info { get; private set; }
  15. public IPEndPoint EndPoint
  16. {
  17. get { return Info.EndPoint; }
  18. }
  19. protected SocketListenerBase(ListenerInfo info)
  20. {
  21. Info = info;
  22. }
  23. /// <summary>
  24. /// Starts to listen
  25. /// </summary>
  26. /// <param name="config">The server config.</param>
  27. /// <returns></returns>
  28. public abstract bool Start(IServerConfig config);
  29. public abstract void Stop();
  30. public event NewClientAcceptHandler NewClientAccepted;
  31. public event ErrorHandler Error;
  32. protected void OnError(Exception e)
  33. {
  34. var handler = Error;
  35. if(handler != null)
  36. handler(this, e);
  37. }
  38. protected void OnError(string errorMessage)
  39. {
  40. OnError(new Exception(errorMessage));
  41. }
  42. protected virtual void OnNewClientAccepted(Socket socket, object state)
  43. {
  44. var handler = NewClientAccepted;
  45. if (handler != null)
  46. handler(this, socket, state);
  47. }
  48. protected void OnNewClientAcceptedAsync(Socket socket, object state)
  49. {
  50. var handler = NewClientAccepted;
  51. if (handler != null)
  52. {
  53. Task task = Task.Run(() => handler(this, socket, state));
  54. //handler.BeginInvoke(this, socket, state, null, null);
  55. }
  56. }
  57. /// <summary>
  58. /// Occurs when [stopped].
  59. /// </summary>
  60. public event EventHandler Stopped;
  61. protected void OnStopped()
  62. {
  63. var handler = Stopped;
  64. if (handler != null)
  65. handler(this, EventArgs.Empty);
  66. }
  67. }
  68. }