jellyfin/Emby.Common.Implementations/Net/UdpSocket.cs

258 lines
8.3 KiB
C#
Raw Normal View History

2016-11-04 01:31:05 -07:00
using System;
2016-10-29 15:22:20 -07:00
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security;
2017-02-05 13:44:08 -07:00
using System.Threading;
2016-10-29 15:22:20 -07:00
using System.Threading.Tasks;
2016-11-08 11:44:23 -07:00
using Emby.Common.Implementations.Networking;
2016-11-04 01:31:05 -07:00
using MediaBrowser.Model.Net;
2016-10-29 15:22:20 -07:00
2016-11-04 01:31:05 -07:00
namespace Emby.Common.Implementations.Net
2016-10-29 15:22:20 -07:00
{
// THIS IS A LINKED FILE - SHARED AMONGST MULTIPLE PLATFORMS
// Be careful to check any changes compile and work for all platform projects it is shared in.
2017-05-25 06:00:14 -07:00
public sealed class UdpSocket : DisposableManagedObjectBase, ISocket
2016-10-29 15:22:20 -07:00
{
2016-11-04 12:51:59 -07:00
private Socket _Socket;
2016-10-29 15:22:20 -07:00
private int _LocalPort;
2017-03-26 09:26:52 -07:00
2017-05-25 06:00:14 -07:00
public Socket Socket
{
get { return _Socket; }
}
2017-03-26 12:00:35 -07:00
private readonly SocketAsyncEventArgs _receiveSocketAsyncEventArgs = new SocketAsyncEventArgs()
{
SocketFlags = SocketFlags.None
};
private readonly SocketAsyncEventArgs _sendSocketAsyncEventArgs = new SocketAsyncEventArgs()
2017-03-26 09:26:52 -07:00
{
SocketFlags = SocketFlags.None
};
private TaskCompletionSource<SocketReceiveResult> _currentReceiveTaskCompletionSource;
2017-03-26 12:00:35 -07:00
private TaskCompletionSource<int> _currentSendTaskCompletionSource;
private readonly SemaphoreSlim _sendLock = new SemaphoreSlim(1, 1);
2016-10-29 15:22:20 -07:00
2016-11-04 12:51:59 -07:00
public UdpSocket(Socket socket, int localPort, IPAddress ip)
2016-10-29 15:22:20 -07:00
{
if (socket == null) throw new ArgumentNullException("socket");
_Socket = socket;
_LocalPort = localPort;
2016-12-04 14:30:38 -07:00
LocalIPAddress = NetworkManager.ToIpAddressInfo(ip);
2016-10-29 15:22:20 -07:00
_Socket.Bind(new IPEndPoint(ip, _LocalPort));
2017-03-26 09:26:52 -07:00
InitReceiveSocketAsyncEventArgs();
}
private void InitReceiveSocketAsyncEventArgs()
{
2017-03-28 10:32:24 -07:00
var receiveBuffer = new byte[8192];
2017-03-26 12:00:35 -07:00
_receiveSocketAsyncEventArgs.SetBuffer(receiveBuffer, 0, receiveBuffer.Length);
2017-03-26 09:26:52 -07:00
_receiveSocketAsyncEventArgs.Completed += _receiveSocketAsyncEventArgs_Completed;
2017-03-26 12:00:35 -07:00
var sendBuffer = new byte[8192];
_sendSocketAsyncEventArgs.SetBuffer(sendBuffer, 0, sendBuffer.Length);
_sendSocketAsyncEventArgs.Completed += _sendSocketAsyncEventArgs_Completed;
2017-03-26 09:26:52 -07:00
}
private void _receiveSocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)
{
var tcs = _currentReceiveTaskCompletionSource;
if (tcs != null)
{
_currentReceiveTaskCompletionSource = null;
2017-03-26 12:00:35 -07:00
if (e.SocketError == SocketError.Success)
2017-03-26 09:26:52 -07:00
{
2017-03-26 12:00:35 -07:00
tcs.TrySetResult(new SocketReceiveResult
{
Buffer = e.Buffer,
ReceivedBytes = e.BytesTransferred,
RemoteEndPoint = ToIpEndPointInfo(e.RemoteEndPoint as IPEndPoint),
LocalIPAddress = LocalIPAddress
});
}
else
{
tcs.TrySetException(new Exception("SocketError: " + e.SocketError));
}
}
}
private void _sendSocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)
{
var tcs = _currentSendTaskCompletionSource;
if (tcs != null)
{
_currentSendTaskCompletionSource = null;
if (e.SocketError == SocketError.Success)
{
tcs.TrySetResult(e.BytesTransferred);
}
else
{
tcs.TrySetException(new Exception("SocketError: " + e.SocketError));
}
2017-03-26 09:26:52 -07:00
}
2016-10-29 15:22:20 -07:00
}
2017-03-02 13:50:09 -07:00
public UdpSocket(Socket socket, IpEndPointInfo endPoint)
{
if (socket == null) throw new ArgumentNullException("socket");
_Socket = socket;
_Socket.Connect(NetworkManager.ToIPEndPoint(endPoint));
2017-03-26 09:26:52 -07:00
InitReceiveSocketAsyncEventArgs();
2017-03-02 13:50:09 -07:00
}
2016-10-29 15:22:20 -07:00
2016-12-04 14:30:38 -07:00
public IpAddressInfo LocalIPAddress
{
get;
private set;
}
2017-05-24 12:12:55 -07:00
public IAsyncResult BeginReceive(byte[] buffer, int offset, int count, AsyncCallback callback)
2016-10-29 15:22:20 -07:00
{
2016-11-04 12:51:59 -07:00
EndPoint receivedFromEndPoint = new IPEndPoint(IPAddress.Any, 0);
2017-03-26 16:53:50 -07:00
2017-05-24 12:12:55 -07:00
return _Socket.BeginReceiveFrom(buffer, offset, count, SocketFlags.None, ref receivedFromEndPoint, callback, buffer);
2016-10-29 15:22:20 -07:00
}
2017-05-24 12:12:55 -07:00
public SocketReceiveResult EndReceive(IAsyncResult result)
2016-10-29 15:22:20 -07:00
{
2017-05-24 12:12:55 -07:00
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint remoteEndPoint = (EndPoint)sender;
2016-10-29 15:22:20 -07:00
2017-05-24 12:12:55 -07:00
var receivedBytes = _Socket.EndReceiveFrom(result, ref remoteEndPoint);
2017-03-26 12:00:35 -07:00
2017-05-24 12:12:55 -07:00
var buffer = (byte[]) result.AsyncState;
2017-03-26 12:00:35 -07:00
2017-05-24 12:12:55 -07:00
return new SocketReceiveResult
2017-03-26 12:54:50 -07:00
{
2017-05-24 12:12:55 -07:00
ReceivedBytes = receivedBytes,
RemoteEndPoint = ToIpEndPointInfo((IPEndPoint)remoteEndPoint),
Buffer = buffer,
LocalIPAddress = LocalIPAddress
};
}
2017-03-26 12:54:50 -07:00
2017-05-24 12:12:55 -07:00
public Task<SocketReceiveResult> ReceiveAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
2017-05-24 21:25:51 -07:00
var taskCompletion = new TaskCompletionSource<SocketReceiveResult>();
Action<IAsyncResult> callback = callbackResult =>
{
try
{
taskCompletion.TrySetResult(EndReceive(callbackResult));
}
catch (Exception ex)
{
taskCompletion.TrySetException(ex);
}
};
var result = BeginReceive(buffer, offset, count, new AsyncCallback(callback));
2017-03-26 12:54:50 -07:00
2017-05-24 21:25:51 -07:00
if (result.CompletedSynchronously)
{
callback(result);
}
cancellationToken.Register(() => taskCompletion.TrySetCanceled());
return taskCompletion.Task;
2017-05-24 12:12:55 -07:00
}
2017-03-26 12:54:50 -07:00
2017-05-24 12:12:55 -07:00
public Task<SocketReceiveResult> ReceiveAsync(CancellationToken cancellationToken)
{
var buffer = new byte[8192];
2017-03-26 12:54:50 -07:00
2017-05-24 12:12:55 -07:00
return ReceiveAsync(buffer, 0, buffer.Length, cancellationToken);
}
2017-03-26 12:54:50 -07:00
2017-05-24 12:12:55 -07:00
public Task SendToAsync(byte[] buffer, int offset, int size, IpEndPointInfo endPoint, CancellationToken cancellationToken)
{
2017-05-24 21:25:51 -07:00
var taskCompletion = new TaskCompletionSource<int>();
Action<IAsyncResult> callback = callbackResult =>
{
try
{
taskCompletion.TrySetResult(EndSendTo(callbackResult));
}
catch (Exception ex)
{
taskCompletion.TrySetException(ex);
}
};
2017-03-26 12:54:50 -07:00
2017-05-24 21:25:51 -07:00
var result = BeginSendTo(buffer, offset, size, endPoint, new AsyncCallback(callback), null);
if (result.CompletedSynchronously)
{
callback(result);
}
cancellationToken.Register(() => taskCompletion.TrySetCanceled());
return taskCompletion.Task;
2017-03-26 12:00:35 -07:00
}
2017-05-24 12:12:55 -07:00
public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, IpEndPointInfo endPoint, AsyncCallback callback, object state)
2017-03-26 12:00:35 -07:00
{
2017-05-24 12:12:55 -07:00
var ipEndPoint = NetworkManager.ToIPEndPoint(endPoint);
2017-02-05 13:44:08 -07:00
2017-05-24 12:12:55 -07:00
return _Socket.BeginSendTo(buffer, offset, size, SocketFlags.None, ipEndPoint, callback, state);
}
2016-10-29 15:22:20 -07:00
2017-05-24 12:12:55 -07:00
public int EndSendTo(IAsyncResult result)
{
return _Socket.EndSendTo(result);
2016-10-29 15:22:20 -07:00
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
var socket = _Socket;
if (socket != null)
socket.Dispose();
2017-03-26 12:00:35 -07:00
_sendLock.Dispose();
2016-10-29 15:22:20 -07:00
2017-03-26 12:00:35 -07:00
var tcs = _currentReceiveTaskCompletionSource;
if (tcs != null)
{
tcs.TrySetCanceled();
}
var sendTcs = _currentSendTaskCompletionSource;
if (sendTcs != null)
{
sendTcs.TrySetCanceled();
}
2016-10-29 15:22:20 -07:00
}
}
2016-11-04 01:31:05 -07:00
private static IpEndPointInfo ToIpEndPointInfo(IPEndPoint endpoint)
{
if (endpoint == null)
{
return null;
}
2016-11-11 00:24:36 -07:00
return NetworkManager.ToIpEndPointInfo(endpoint);
2016-11-04 01:31:05 -07:00
}
2016-10-29 15:22:20 -07:00
}
2016-11-04 01:31:05 -07:00
}