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

263 lines
8.2 KiB
C#
Raw Normal View History

#pragma warning disable CS1591
using System;
2016-10-29 15:22:20 -07:00
using System.Net;
using System.Net.Sockets;
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-04 01:31:05 -07:00
using MediaBrowser.Model.Net;
2016-10-29 15:22:20 -07:00
namespace Emby.Server.Implementations.Net
2016-10-29 15:22:20 -07:00
{
2019-01-07 16:24:34 -07:00
// THIS IS A LINKED FILE - SHARED AMONGST MULTIPLE PLATFORMS
2016-10-29 15:22:20 -07: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 15:22:20 -07:00
{
private Socket _socket;
private int _localPort;
private bool _disposed = false;
2017-03-26 09:26:52 -07:00
public Socket Socket => _socket;
public IPAddress LocalIPAddress { get; }
2017-05-25 06:00:14 -07:00
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;
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(nameof(socket));
2016-10-29 15:22:20 -07:00
_socket = socket;
_localPort = localPort;
LocalIPAddress = 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 = e.RemoteEndPoint as IPEndPoint,
2017-03-26 12:00:35 -07: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 09:26:52 -07:00
}
2016-10-29 15:22:20 -07:00
}
public UdpSocket(Socket socket, IPEndPoint endPoint)
2017-03-02 13:50:09 -07:00
{
if (socket == null) throw new ArgumentNullException(nameof(socket));
2017-03-02 13:50:09 -07:00
_socket = socket;
_socket.Connect(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
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
{
2018-09-12 10:26:21 -07:00
ThrowIfDisposed();
2016-11-04 12:51:59 -07:00
EndPoint receivedFromEndPoint = new IPEndPoint(IPAddress.Any, 0);
2017-03-26 16:53:50 -07:00
return _socket.BeginReceiveFrom(buffer, offset, count, SocketFlags.None, ref receivedFromEndPoint, callback, buffer);
2016-10-29 15:22:20 -07:00
}
2017-05-31 23:25:07 -07:00
public int Receive(byte[] buffer, int offset, int count)
{
2018-09-12 10:26:21 -07:00
ThrowIfDisposed();
return _socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
2017-05-31 23:25:07 -07:00
}
2017-05-24 12:12:55 -07:00
public SocketReceiveResult EndReceive(IAsyncResult result)
2016-10-29 15:22:20 -07:00
{
2018-09-12 10:26:21 -07:00
ThrowIfDisposed();
2019-01-13 13:37:13 -07:00
var sender = new IPEndPoint(IPAddress.Any, 0);
var remoteEndPoint = (EndPoint)sender;
2016-10-29 15:22:20 -07:00
var receivedBytes = _socket.EndReceiveFrom(result, ref remoteEndPoint);
2017-03-26 12:00:35 -07:00
2018-09-12 10:26:21 -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 = (IPEndPoint)remoteEndPoint,
2017-05-24 12:12:55 -07:00
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)
{
2018-09-12 10:26:21 -07:00
ThrowIfDisposed();
2017-05-24 21:25:51 -07:00
var taskCompletion = new TaskCompletionSource<SocketReceiveResult>();
2018-09-12 10:26:21 -07:00
bool isResultSet = false;
2017-05-24 21:25:51 -07:00
Action<IAsyncResult> callback = callbackResult =>
{
try
{
2018-09-12 10:26:21 -07:00
if (!isResultSet)
{
isResultSet = true;
taskCompletion.TrySetResult(EndReceive(callbackResult));
}
2017-05-24 21:25:51 -07:00
}
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);
2018-09-12 10:26:21 -07:00
return taskCompletion.Task;
2017-05-24 21:25:51 -07:00
}
cancellationToken.Register(() => taskCompletion.TrySetCanceled());
return taskCompletion.Task;
2017-05-24 12:12:55 -07:00
}
2017-03-26 12:54:50 -07:00
public Task SendToAsync(byte[] buffer, int offset, int size, IPEndPoint endPoint, CancellationToken cancellationToken)
2017-05-24 12:12:55 -07:00
{
2018-09-12 10:26:21 -07:00
ThrowIfDisposed();
2017-05-24 21:25:51 -07:00
var taskCompletion = new TaskCompletionSource<int>();
2018-09-12 10:26:21 -07:00
bool isResultSet = false;
2017-05-24 21:25:51 -07:00
Action<IAsyncResult> callback = callbackResult =>
{
try
{
2018-09-12 10:26:21 -07:00
if (!isResultSet)
{
isResultSet = true;
taskCompletion.TrySetResult(EndSendTo(callbackResult));
}
2017-05-24 21:25:51 -07:00
}
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);
2018-09-12 10:26:21 -07:00
return taskCompletion.Task;
2017-05-24 21:25:51 -07:00
}
cancellationToken.Register(() => taskCompletion.TrySetCanceled());
return taskCompletion.Task;
2017-03-26 12:00:35 -07:00
}
public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, IPEndPoint endPoint, AsyncCallback callback, object state)
2017-03-26 12:00:35 -07:00
{
2018-09-12 10:26:21 -07:00
ThrowIfDisposed();
return _socket.BeginSendTo(buffer, offset, size, SocketFlags.None, endPoint, callback, state);
2017-05-24 12:12:55 -07:00
}
2016-10-29 15:22:20 -07:00
2017-05-24 12:12:55 -07:00
public int EndSendTo(IAsyncResult result)
{
2018-09-12 10:26:21 -07:00
ThrowIfDisposed();
return _socket.EndSendTo(result);
2016-10-29 15:22:20 -07:00
}
private void ThrowIfDisposed()
2016-10-29 15:22:20 -07:00
{
if (_disposed)
2016-10-29 15:22:20 -07:00
{
throw new ObjectDisposedException(nameof(UdpSocket));
}
}
2016-10-29 15:22:20 -07:00
public void Dispose()
{
if (_disposed)
{
return;
2016-10-29 15:22:20 -07:00
}
_socket?.Dispose();
_currentReceiveTaskCompletionSource?.TrySetCanceled();
_currentSendTaskCompletionSource?.TrySetCanceled();
_socket = null;
_currentReceiveTaskCompletionSource = null;
_currentSendTaskCompletionSource = null;
_disposed = true;
2016-10-29 15:22:20 -07:00
}
}
2016-11-04 01:31:05 -07:00
}