Datagram.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using MediaBrowser.Model.Logging;
  2. using System;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Text;
  6. namespace MediaBrowser.Dlna.Ssdp
  7. {
  8. public class Datagram
  9. {
  10. public IPEndPoint ToEndPoint { get; private set; }
  11. public IPEndPoint FromEndPoint { get; private set; }
  12. public string Message { get; private set; }
  13. /// <summary>
  14. /// The number of times to send the message
  15. /// </summary>
  16. public int TotalSendCount { get; private set; }
  17. /// <summary>
  18. /// The number of times the message has been sent
  19. /// </summary>
  20. public int SendCount { get; private set; }
  21. private readonly ILogger _logger;
  22. public Datagram(IPEndPoint toEndPoint, IPEndPoint fromEndPoint, ILogger logger, string message, int totalSendCount)
  23. {
  24. Message = message;
  25. _logger = logger;
  26. TotalSendCount = totalSendCount;
  27. FromEndPoint = fromEndPoint;
  28. ToEndPoint = toEndPoint;
  29. }
  30. public void Send()
  31. {
  32. var msg = Encoding.ASCII.GetBytes(Message);
  33. try
  34. {
  35. var client = CreateSocket();
  36. if (FromEndPoint != null)
  37. {
  38. client.Bind(FromEndPoint);
  39. }
  40. client.BeginSendTo(msg, 0, msg.Length, SocketFlags.None, ToEndPoint, result =>
  41. {
  42. try
  43. {
  44. client.EndSend(result);
  45. }
  46. catch (Exception ex)
  47. {
  48. _logger.ErrorException("Error sending Datagram to {0} from {1}: " + Message, ex, ToEndPoint, FromEndPoint == null ? "" : FromEndPoint.ToString());
  49. }
  50. finally
  51. {
  52. try
  53. {
  54. client.Close();
  55. }
  56. catch (Exception)
  57. {
  58. }
  59. }
  60. }, null);
  61. }
  62. catch (Exception ex)
  63. {
  64. _logger.ErrorException("Error sending Datagram to {0} from {1}: " + Message, ex, ToEndPoint, FromEndPoint == null ? "" : FromEndPoint.ToString());
  65. }
  66. ++SendCount;
  67. }
  68. private Socket CreateSocket()
  69. {
  70. var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  71. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  72. return socket;
  73. }
  74. }
  75. }