2014-04-10 15:06:54 +00:00
|
|
|
|
using MediaBrowser.Model.Logging;
|
|
|
|
|
using System;
|
|
|
|
|
using System.Net;
|
|
|
|
|
using System.Net.Sockets;
|
|
|
|
|
using System.Text;
|
|
|
|
|
|
2014-04-25 17:30:41 +00:00
|
|
|
|
namespace MediaBrowser.Dlna.Ssdp
|
2014-04-10 15:06:54 +00:00
|
|
|
|
{
|
|
|
|
|
public class Datagram
|
|
|
|
|
{
|
|
|
|
|
public IPEndPoint EndPoint { get; private set; }
|
|
|
|
|
public IPAddress LocalAddress { get; private set; }
|
|
|
|
|
public string Message { get; private set; }
|
|
|
|
|
|
2014-04-25 17:30:41 +00:00
|
|
|
|
/// <summary>
|
|
|
|
|
/// The number of times to send the message
|
|
|
|
|
/// </summary>
|
|
|
|
|
public int TotalSendCount { get; private set; }
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// The number of times the message has been sent
|
|
|
|
|
/// </summary>
|
2014-04-10 15:06:54 +00:00
|
|
|
|
public int SendCount { get; private set; }
|
|
|
|
|
|
|
|
|
|
private readonly ILogger _logger;
|
|
|
|
|
|
2014-04-25 17:30:41 +00:00
|
|
|
|
public Datagram(IPEndPoint endPoint, IPAddress localAddress, ILogger logger, string message, int totalSendCount)
|
2014-04-10 15:06:54 +00:00
|
|
|
|
{
|
|
|
|
|
Message = message;
|
|
|
|
|
_logger = logger;
|
2014-04-25 17:30:41 +00:00
|
|
|
|
TotalSendCount = totalSendCount;
|
2014-04-10 15:06:54 +00:00
|
|
|
|
LocalAddress = localAddress;
|
|
|
|
|
EndPoint = endPoint;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Send()
|
|
|
|
|
{
|
|
|
|
|
var msg = Encoding.ASCII.GetBytes(Message);
|
|
|
|
|
try
|
|
|
|
|
{
|
2014-04-25 17:30:41 +00:00
|
|
|
|
var client = CreateSocket();
|
|
|
|
|
|
|
|
|
|
client.Bind(new IPEndPoint(LocalAddress, 0));
|
|
|
|
|
|
|
|
|
|
client.BeginSendTo(msg, 0, msg.Length, SocketFlags.None, EndPoint, result =>
|
2014-04-10 15:06:54 +00:00
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
client.EndSend(result);
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
_logger.ErrorException("Error sending Datagram", ex);
|
|
|
|
|
}
|
|
|
|
|
finally
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
client.Close();
|
|
|
|
|
}
|
|
|
|
|
catch (Exception)
|
|
|
|
|
{
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}, null);
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
_logger.ErrorException("Error sending Datagram", ex);
|
|
|
|
|
}
|
|
|
|
|
++SendCount;
|
|
|
|
|
}
|
2014-04-25 17:30:41 +00:00
|
|
|
|
|
|
|
|
|
private Socket CreateSocket()
|
|
|
|
|
{
|
|
|
|
|
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
|
|
|
|
|
|
|
|
|
|
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
|
|
|
|
return socket;
|
|
|
|
|
}
|
2014-04-10 15:06:54 +00:00
|
|
|
|
}
|
|
|
|
|
}
|