NetSocket.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Threading;
  5. using Emby.Common.Implementations.Networking;
  6. using MediaBrowser.Model.Net;
  7. using MediaBrowser.Model.Logging;
  8. namespace Emby.Common.Implementations.Net
  9. {
  10. public class NetSocket : ISocket
  11. {
  12. public Socket Socket { get; private set; }
  13. private readonly ILogger _logger;
  14. public NetSocket(Socket socket, ILogger logger)
  15. {
  16. if (socket == null)
  17. {
  18. throw new ArgumentNullException("socket");
  19. }
  20. if (logger == null)
  21. {
  22. throw new ArgumentNullException("logger");
  23. }
  24. Socket = socket;
  25. _logger = logger;
  26. }
  27. public IpEndPointInfo LocalEndPoint
  28. {
  29. get
  30. {
  31. return NetworkManager.ToIpEndPointInfo((IPEndPoint)Socket.LocalEndPoint);
  32. }
  33. }
  34. public IpEndPointInfo RemoteEndPoint
  35. {
  36. get
  37. {
  38. return NetworkManager.ToIpEndPointInfo((IPEndPoint)Socket.RemoteEndPoint);
  39. }
  40. }
  41. public void Close()
  42. {
  43. #if NET46
  44. Socket.Close();
  45. #else
  46. Socket.Dispose();
  47. #endif
  48. }
  49. public void Shutdown(bool both)
  50. {
  51. if (both)
  52. {
  53. Socket.Shutdown(SocketShutdown.Both);
  54. }
  55. else
  56. {
  57. // Change interface if ever needed
  58. throw new NotImplementedException();
  59. }
  60. }
  61. public void Listen(int backlog)
  62. {
  63. Socket.Listen(backlog);
  64. }
  65. public void Bind(IpEndPointInfo endpoint)
  66. {
  67. var nativeEndpoint = NetworkManager.ToIPEndPoint(endpoint);
  68. Socket.Bind(nativeEndpoint);
  69. }
  70. private SocketAcceptor _acceptor;
  71. public void StartAccept(Action<ISocket> onAccept, Func<bool> isClosed)
  72. {
  73. _acceptor = new SocketAcceptor(_logger, Socket, onAccept, isClosed);
  74. _acceptor.StartAccept();
  75. }
  76. public void Dispose()
  77. {
  78. Socket.Dispose();
  79. }
  80. }
  81. }