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

296 lines
9.4 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-03-02 13:50:09 -07:00
internal 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
private SocketAsyncEventArgs _receiveSocketAsyncEventArgs = new SocketAsyncEventArgs()
{
SocketFlags = SocketFlags.None
};
private TaskCompletionSource<SocketReceiveResult> _currentReceiveTaskCompletionSource;
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()
{
var buffer = new byte[8192];
_receiveSocketAsyncEventArgs.SetBuffer(buffer, 0, buffer.Length);
_receiveSocketAsyncEventArgs.Completed += _receiveSocketAsyncEventArgs_Completed;
}
private void _receiveSocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)
{
var tcs = _currentReceiveTaskCompletionSource;
if (tcs != null)
{
_currentReceiveTaskCompletionSource = null;
tcs.TrySetResult(new SocketReceiveResult
{
Buffer = e.Buffer,
ReceivedBytes = e.BytesTransferred,
RemoteEndPoint = ToIpEndPointInfo(e.RemoteEndPoint as IPEndPoint),
LocalIPAddress = LocalIPAddress
});
}
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-03-02 13:50:09 -07:00
#region ISocket Members
2016-10-29 15:22:20 -07:00
2017-03-02 13:50:09 -07:00
public Task<SocketReceiveResult> ReceiveAsync(CancellationToken cancellationToken)
2016-10-29 15:22:20 -07:00
{
ThrowIfDisposed();
2016-11-04 11:56:47 -07:00
var tcs = new TaskCompletionSource<SocketReceiveResult>();
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-12 21:49:10 -07:00
cancellationToken.Register(() => tcs.TrySetCanceled());
2016-10-29 15:22:20 -07:00
#if NETSTANDARD1_6
2017-03-26 09:26:52 -07:00
var state = new AsyncReceiveState(_Socket, receivedFromEndPoint);
state.TaskCompletionSource = tcs;
2017-02-05 13:44:08 -07:00
_Socket.ReceiveFromAsync(new ArraySegment<Byte>(state.Buffer), SocketFlags.None, state.RemoteEndPoint)
2016-10-29 15:22:20 -07:00
.ContinueWith((task, asyncState) =>
{
if (task.Status != TaskStatus.Faulted)
{
var receiveState = asyncState as AsyncReceiveState;
2016-12-04 14:30:38 -07:00
receiveState.RemoteEndPoint = task.Result.RemoteEndPoint;
ProcessResponse(receiveState, () => task.Result.ReceivedBytes, LocalIPAddress);
2016-10-29 15:22:20 -07:00
}
}, state);
#else
2017-03-26 09:26:52 -07:00
//var state = new AsyncReceiveState(_Socket, receivedFromEndPoint);
//state.TaskCompletionSource = tcs;
//_Socket.BeginReceiveFrom(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, ref state.RemoteEndPoint, ProcessResponse, state);
_receiveSocketAsyncEventArgs.RemoteEndPoint = receivedFromEndPoint;
_currentReceiveTaskCompletionSource = tcs;
var isPending = _Socket.ReceiveFromAsync(_receiveSocketAsyncEventArgs);
2016-10-29 15:22:20 -07:00
#endif
return tcs.Task;
}
2017-02-05 13:44:08 -07:00
public Task SendAsync(byte[] buffer, int size, IpEndPointInfo endPoint, CancellationToken cancellationToken)
2016-10-29 15:22:20 -07:00
{
ThrowIfDisposed();
2016-11-04 11:56:47 -07:00
if (buffer == null) throw new ArgumentNullException("messageData");
2016-10-29 15:22:20 -07:00
if (endPoint == null) throw new ArgumentNullException("endPoint");
2016-12-04 14:30:38 -07:00
var ipEndPoint = NetworkManager.ToIPEndPoint(endPoint);
2016-10-29 15:22:20 -07:00
#if NETSTANDARD1_6
2016-11-04 11:56:47 -07:00
if (size != buffer.Length)
{
byte[] copy = new byte[size];
Buffer.BlockCopy(buffer, 0, copy, 0, size);
buffer = copy;
}
2017-02-05 13:44:08 -07:00
cancellationToken.ThrowIfCancellationRequested();
2016-12-04 14:30:38 -07:00
_Socket.SendTo(buffer, ipEndPoint);
2016-10-29 15:22:20 -07:00
return Task.FromResult(true);
#else
var taskSource = new TaskCompletionSource<bool>();
try
{
2016-12-04 14:30:38 -07:00
_Socket.BeginSendTo(buffer, 0, size, SocketFlags.None, ipEndPoint, result =>
2016-10-29 15:22:20 -07:00
{
2017-02-05 13:44:08 -07:00
if (cancellationToken.IsCancellationRequested)
{
taskSource.TrySetCanceled();
return;
}
2016-10-29 15:22:20 -07:00
try
{
_Socket.EndSend(result);
taskSource.TrySetResult(true);
}
2016-11-14 12:48:01 -07:00
catch (Exception ex)
2016-10-29 15:22:20 -07:00
{
taskSource.TrySetException(ex);
}
2016-11-04 16:57:21 -07:00
2016-10-29 15:22:20 -07:00
}, null);
}
2016-11-04 16:57:21 -07:00
catch (Exception ex)
2016-10-29 15:22:20 -07:00
{
taskSource.TrySetException(ex);
}
2016-12-04 14:30:38 -07:00
//_Socket.SendTo(messageData, new System.Net.IPEndPoint(IPAddress.Parse(RemoteEndPoint.IPAddress), RemoteEndPoint.Port));
2016-10-29 15:22:20 -07:00
return taskSource.Task;
#endif
}
#endregion
#region Overrides
protected override void Dispose(bool disposing)
{
if (disposing)
{
var socket = _Socket;
if (socket != null)
socket.Dispose();
}
}
#endregion
#region Private Methods
2016-12-04 14:30:38 -07:00
private static void ProcessResponse(AsyncReceiveState state, Func<int> receiveData, IpAddressInfo localIpAddress)
2016-10-29 15:22:20 -07:00
{
try
{
var bytesRead = receiveData();
2016-12-04 14:30:38 -07:00
var ipEndPoint = state.RemoteEndPoint as IPEndPoint;
2017-03-12 21:49:10 -07:00
state.TaskCompletionSource.TrySetResult(
2016-12-04 14:30:38 -07:00
new SocketReceiveResult
2016-10-29 15:22:20 -07:00
{
Buffer = state.Buffer,
ReceivedBytes = bytesRead,
2016-12-04 14:30:38 -07:00
RemoteEndPoint = ToIpEndPointInfo(ipEndPoint),
LocalIPAddress = localIpAddress
2016-10-29 15:22:20 -07:00
}
);
}
catch (ObjectDisposedException)
{
2017-03-12 21:49:10 -07:00
state.TaskCompletionSource.TrySetCanceled();
2016-10-29 15:22:20 -07:00
}
catch (SocketException se)
{
if (se.SocketErrorCode != SocketError.Interrupted && se.SocketErrorCode != SocketError.OperationAborted && se.SocketErrorCode != SocketError.Shutdown)
2017-03-12 21:49:10 -07:00
state.TaskCompletionSource.TrySetException(se);
2016-10-29 15:22:20 -07:00
else
2017-03-12 21:49:10 -07:00
state.TaskCompletionSource.TrySetCanceled();
2016-10-29 15:22:20 -07:00
}
catch (Exception ex)
{
2017-03-12 21:49:10 -07:00
state.TaskCompletionSource.TrySetException(ex);
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
private void ProcessResponse(IAsyncResult asyncResult)
{
#if NET46
var state = asyncResult.AsyncState as AsyncReceiveState;
try
{
2016-12-04 14:30:38 -07:00
var bytesRead = state.Socket.EndReceiveFrom(asyncResult, ref state.RemoteEndPoint);
2016-10-29 15:22:20 -07:00
2016-12-04 14:30:38 -07:00
var ipEndPoint = state.RemoteEndPoint as IPEndPoint;
2017-03-12 21:49:10 -07:00
state.TaskCompletionSource.TrySetResult(
2016-11-04 11:56:47 -07:00
new SocketReceiveResult
2016-10-29 15:22:20 -07:00
{
Buffer = state.Buffer,
ReceivedBytes = bytesRead,
2016-12-04 14:30:38 -07:00
RemoteEndPoint = ToIpEndPointInfo(ipEndPoint),
LocalIPAddress = LocalIPAddress
2016-10-29 15:22:20 -07:00
}
);
}
catch (ObjectDisposedException)
{
2017-03-12 21:49:10 -07:00
state.TaskCompletionSource.TrySetCanceled();
2016-10-29 15:22:20 -07:00
}
catch (Exception ex)
{
2017-03-12 21:49:10 -07:00
state.TaskCompletionSource.TrySetException(ex);
2016-10-29 15:22:20 -07:00
}
#endif
}
#endregion
#region Private Classes
private class AsyncReceiveState
{
2016-12-04 14:30:38 -07:00
public AsyncReceiveState(Socket socket, EndPoint remoteEndPoint)
2016-10-29 15:22:20 -07:00
{
this.Socket = socket;
2016-12-04 14:30:38 -07:00
this.RemoteEndPoint = remoteEndPoint;
2016-10-29 15:22:20 -07:00
}
2016-12-04 14:30:38 -07:00
public EndPoint RemoteEndPoint;
2016-11-04 01:31:05 -07:00
public byte[] Buffer = new byte[8192];
2016-10-29 15:22:20 -07:00
2016-11-04 12:51:59 -07:00
public Socket Socket { get; private set; }
2016-10-29 15:22:20 -07:00
2016-11-04 11:56:47 -07:00
public TaskCompletionSource<SocketReceiveResult> TaskCompletionSource { get; set; }
2016-10-29 15:22:20 -07:00
}
#endregion
}
2016-11-04 01:31:05 -07:00
}