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

284 lines
8.9 KiB
C#
Raw Normal View History

2016-11-04 08:31:05 +00:00
using System;
2016-10-29 22:22:20 +00:00
using System.Net;
using System.Net.Sockets;
2017-02-05 20:44:08 +00:00
using System.Threading;
2016-10-29 22:22:20 +00:00
using System.Threading.Tasks;
using Emby.Server.Implementations.Networking;
2016-11-04 08:31:05 +00:00
using MediaBrowser.Model.Net;
2016-10-29 22:22:20 +00:00
namespace Emby.Server.Implementations.Net
2016-10-29 22:22:20 +00: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 13:00:14 +00:00
public sealed class UdpSocket : DisposableManagedObjectBase, ISocket
2016-10-29 22:22:20 +00:00
{
2016-11-04 19:51:59 +00:00
private Socket _Socket;
2016-10-29 22:22:20 +00:00
private int _LocalPort;
2017-03-26 16:26:52 +00:00
2017-05-25 13:00:14 +00:00
public Socket Socket
{
get { return _Socket; }
}
2017-03-26 19:00:35 +00:00
private readonly SocketAsyncEventArgs _receiveSocketAsyncEventArgs = new SocketAsyncEventArgs()
{
SocketFlags = SocketFlags.None
};
private readonly SocketAsyncEventArgs _sendSocketAsyncEventArgs = new SocketAsyncEventArgs()
2017-03-26 16:26:52 +00:00
{
SocketFlags = SocketFlags.None
};
private TaskCompletionSource<SocketReceiveResult> _currentReceiveTaskCompletionSource;
2017-03-26 19:00:35 +00:00
private TaskCompletionSource<int> _currentSendTaskCompletionSource;
2016-11-04 19:51:59 +00:00
public UdpSocket(Socket socket, int localPort, IPAddress ip)
2016-10-29 22:22:20 +00:00
{
if (socket == null) throw new ArgumentNullException("socket");
_Socket = socket;
_LocalPort = localPort;
2016-12-04 21:30:38 +00:00
LocalIPAddress = NetworkManager.ToIpAddressInfo(ip);
2016-10-29 22:22:20 +00:00
_Socket.Bind(new IPEndPoint(ip, _LocalPort));
2017-03-26 16:26:52 +00:00
InitReceiveSocketAsyncEventArgs();
}
private void InitReceiveSocketAsyncEventArgs()
{
2017-03-28 17:32:24 +00:00
var receiveBuffer = new byte[8192];
2017-03-26 19:00:35 +00:00
_receiveSocketAsyncEventArgs.SetBuffer(receiveBuffer, 0, receiveBuffer.Length);
2017-03-26 16:26:52 +00:00
_receiveSocketAsyncEventArgs.Completed += _receiveSocketAsyncEventArgs_Completed;
2017-03-26 19:00:35 +00:00
var sendBuffer = new byte[8192];
_sendSocketAsyncEventArgs.SetBuffer(sendBuffer, 0, sendBuffer.Length);
_sendSocketAsyncEventArgs.Completed += _sendSocketAsyncEventArgs_Completed;
2017-03-26 16:26:52 +00:00
}
private void _receiveSocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)
{
var tcs = _currentReceiveTaskCompletionSource;
if (tcs != null)
{
_currentReceiveTaskCompletionSource = null;
2017-03-26 19:00:35 +00:00
if (e.SocketError == SocketError.Success)
2017-03-26 16:26:52 +00:00
{
2017-03-26 19:00:35 +00: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 16:26:52 +00:00
}
2016-10-29 22:22:20 +00:00
}
2017-03-02 20:50:09 +00:00
public UdpSocket(Socket socket, IpEndPointInfo endPoint)
{
if (socket == null) throw new ArgumentNullException("socket");
_Socket = socket;
_Socket.Connect(NetworkManager.ToIPEndPoint(endPoint));
2017-03-26 16:26:52 +00:00
InitReceiveSocketAsyncEventArgs();
2017-03-02 20:50:09 +00:00
}
2016-10-29 22:22:20 +00:00
2016-12-04 21:30:38 +00:00
public IpAddressInfo LocalIPAddress
{
get;
private set;
}
2017-05-24 19:12:55 +00:00
public IAsyncResult BeginReceive(byte[] buffer, int offset, int count, AsyncCallback callback)
2016-10-29 22:22:20 +00:00
{
2018-09-12 17:26:21 +00:00
ThrowIfDisposed();
2016-11-04 19:51:59 +00:00
EndPoint receivedFromEndPoint = new IPEndPoint(IPAddress.Any, 0);
2017-03-26 23:53:50 +00:00
2017-05-24 19:12:55 +00:00
return _Socket.BeginReceiveFrom(buffer, offset, count, SocketFlags.None, ref receivedFromEndPoint, callback, buffer);
2016-10-29 22:22:20 +00:00
}
2017-06-01 06:25:07 +00:00
public int Receive(byte[] buffer, int offset, int count)
{
2018-09-12 17:26:21 +00:00
ThrowIfDisposed();
2017-06-01 06:25:07 +00:00
return _Socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
}
2017-05-24 19:12:55 +00:00
public SocketReceiveResult EndReceive(IAsyncResult result)
2016-10-29 22:22:20 +00:00
{
2018-09-12 17:26:21 +00:00
ThrowIfDisposed();
2017-05-24 19:12:55 +00:00
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint remoteEndPoint = (EndPoint)sender;
2016-10-29 22:22:20 +00:00
2017-05-24 19:12:55 +00:00
var receivedBytes = _Socket.EndReceiveFrom(result, ref remoteEndPoint);
2017-03-26 19:00:35 +00:00
2018-09-12 17:26:21 +00:00
var buffer = (byte[])result.AsyncState;
2017-03-26 19:00:35 +00:00
2017-05-24 19:12:55 +00:00
return new SocketReceiveResult
2017-03-26 19:54:50 +00:00
{
2017-05-24 19:12:55 +00:00
ReceivedBytes = receivedBytes,
RemoteEndPoint = ToIpEndPointInfo((IPEndPoint)remoteEndPoint),
Buffer = buffer,
LocalIPAddress = LocalIPAddress
};
}
2017-03-26 19:54:50 +00:00
2017-05-24 19:12:55 +00:00
public Task<SocketReceiveResult> ReceiveAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
2018-09-12 17:26:21 +00:00
ThrowIfDisposed();
2017-05-25 04:25:51 +00:00
var taskCompletion = new TaskCompletionSource<SocketReceiveResult>();
2018-09-12 17:26:21 +00:00
bool isResultSet = false;
2017-05-25 04:25:51 +00:00
Action<IAsyncResult> callback = callbackResult =>
{
try
{
2018-09-12 17:26:21 +00:00
if (!isResultSet)
{
isResultSet = true;
taskCompletion.TrySetResult(EndReceive(callbackResult));
}
2017-05-25 04:25:51 +00:00
}
catch (Exception ex)
{
taskCompletion.TrySetException(ex);
}
};
var result = BeginReceive(buffer, offset, count, new AsyncCallback(callback));
2017-03-26 19:54:50 +00:00
2017-05-25 04:25:51 +00:00
if (result.CompletedSynchronously)
{
callback(result);
2018-09-12 17:26:21 +00:00
return taskCompletion.Task;
2017-05-25 04:25:51 +00:00
}
cancellationToken.Register(() => taskCompletion.TrySetCanceled());
return taskCompletion.Task;
2017-05-24 19:12:55 +00:00
}
2017-03-26 19:54:50 +00:00
2017-05-24 19:12:55 +00:00
public Task<SocketReceiveResult> ReceiveAsync(CancellationToken cancellationToken)
{
2018-09-12 17:26:21 +00:00
ThrowIfDisposed();
2017-05-24 19:12:55 +00:00
var buffer = new byte[8192];
2017-03-26 19:54:50 +00:00
2017-05-24 19:12:55 +00:00
return ReceiveAsync(buffer, 0, buffer.Length, cancellationToken);
}
2017-03-26 19:54:50 +00:00
2017-05-24 19:12:55 +00:00
public Task SendToAsync(byte[] buffer, int offset, int size, IpEndPointInfo endPoint, CancellationToken cancellationToken)
{
2018-09-12 17:26:21 +00:00
ThrowIfDisposed();
2017-05-25 04:25:51 +00:00
var taskCompletion = new TaskCompletionSource<int>();
2018-09-12 17:26:21 +00:00
bool isResultSet = false;
2017-05-25 04:25:51 +00:00
Action<IAsyncResult> callback = callbackResult =>
{
try
{
2018-09-12 17:26:21 +00:00
if (!isResultSet)
{
isResultSet = true;
taskCompletion.TrySetResult(EndSendTo(callbackResult));
}
2017-05-25 04:25:51 +00:00
}
catch (Exception ex)
{
taskCompletion.TrySetException(ex);
}
};
2017-03-26 19:54:50 +00:00
2017-05-25 04:25:51 +00:00
var result = BeginSendTo(buffer, offset, size, endPoint, new AsyncCallback(callback), null);
if (result.CompletedSynchronously)
{
callback(result);
2018-09-12 17:26:21 +00:00
return taskCompletion.Task;
2017-05-25 04:25:51 +00:00
}
cancellationToken.Register(() => taskCompletion.TrySetCanceled());
return taskCompletion.Task;
2017-03-26 19:00:35 +00:00
}
2017-05-24 19:12:55 +00:00
public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, IpEndPointInfo endPoint, AsyncCallback callback, object state)
2017-03-26 19:00:35 +00:00
{
2018-09-12 17:26:21 +00:00
ThrowIfDisposed();
2017-05-24 19:12:55 +00:00
var ipEndPoint = NetworkManager.ToIPEndPoint(endPoint);
2017-02-05 20:44:08 +00:00
2017-05-24 19:12:55 +00:00
return _Socket.BeginSendTo(buffer, offset, size, SocketFlags.None, ipEndPoint, callback, state);
}
2016-10-29 22:22:20 +00:00
2017-05-24 19:12:55 +00:00
public int EndSendTo(IAsyncResult result)
{
2018-09-12 17:26:21 +00:00
ThrowIfDisposed();
2017-05-24 19:12:55 +00:00
return _Socket.EndSendTo(result);
2016-10-29 22:22:20 +00:00
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
var socket = _Socket;
if (socket != null)
socket.Dispose();
2017-03-26 19:00:35 +00:00
var tcs = _currentReceiveTaskCompletionSource;
if (tcs != null)
{
tcs.TrySetCanceled();
}
var sendTcs = _currentSendTaskCompletionSource;
if (sendTcs != null)
{
sendTcs.TrySetCanceled();
}
2016-10-29 22:22:20 +00:00
}
}
2016-11-04 08:31:05 +00:00
private static IpEndPointInfo ToIpEndPointInfo(IPEndPoint endpoint)
{
if (endpoint == null)
{
return null;
}
2016-11-11 07:24:36 +00:00
return NetworkManager.ToIpEndPointInfo(endpoint);
2016-11-04 08:31:05 +00:00
}
2016-10-29 22:22:20 +00:00
}
2016-11-04 08:31:05 +00:00
}