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

270 lines
8.4 KiB
C#
Raw Normal View History

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;
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
{
2019-01-07 23:24:34 +00:00
// THIS IS A LINKED FILE - SHARED AMONGST MULTIPLE PLATFORMS
2016-10-29 22:22:20 +00:00
// Be careful to check any changes compile and work for all platform projects it is shared in.
public sealed class UdpSocket : ISocket, IDisposable
2016-10-29 22:22:20 +00:00
{
private Socket _socket;
private int _localPort;
private bool _disposed = false;
2017-03-26 16:26:52 +00:00
public Socket Socket => _socket;
public IPAddress LocalIPAddress { get; }
2017-05-25 13:00:14 +00:00
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(nameof(socket));
2016-10-29 22:22:20 +00:00
_socket = socket;
_localPort = localPort;
LocalIPAddress = 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 = e.RemoteEndPoint as IPEndPoint,
2017-03-26 19:00:35 +00:00
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
}
public UdpSocket(Socket socket, IPEndPoint endPoint)
2017-03-02 20:50:09 +00:00
{
if (socket == null) throw new ArgumentNullException(nameof(socket));
2017-03-02 20:50:09 +00:00
_socket = socket;
_socket.Connect(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
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
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();
return _socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
2017-06-01 06:25:07 +00:00
}
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();
2019-01-13 20:37:13 +00:00
var sender = new IPEndPoint(IPAddress.Any, 0);
var remoteEndPoint = (EndPoint)sender;
2016-10-29 22:22:20 +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 = (IPEndPoint)remoteEndPoint,
2017-05-24 19:12:55 +00:00
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
public Task SendToAsync(byte[] buffer, int offset, int size, IPEndPoint endPoint, CancellationToken cancellationToken)
2017-05-24 19:12:55 +00:00
{
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
}
public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, IPEndPoint endPoint, AsyncCallback callback, object state)
2017-03-26 19:00:35 +00:00
{
2018-09-12 17:26:21 +00:00
ThrowIfDisposed();
return _socket.BeginSendTo(buffer, offset, size, SocketFlags.None, endPoint, callback, state);
2017-05-24 19:12:55 +00:00
}
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();
return _socket.EndSendTo(result);
2016-10-29 22:22:20 +00:00
}
private void ThrowIfDisposed()
2016-10-29 22:22:20 +00:00
{
if (_disposed)
2016-10-29 22:22:20 +00:00
{
throw new ObjectDisposedException(nameof(UdpSocket));
}
}
2016-10-29 22:22:20 +00:00
public void Dispose()
{
if (_disposed)
{
return;
2016-10-29 22:22:20 +00:00
}
_socket?.Dispose();
_currentReceiveTaskCompletionSource?.TrySetCanceled();
_currentSendTaskCompletionSource?.TrySetCanceled();
_socket = null;
_currentReceiveTaskCompletionSource = null;
_currentSendTaskCompletionSource = null;
_disposed = true;
2016-10-29 22:22:20 +00:00
}
}
2016-11-04 08:31:05 +00:00
}