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

325 lines
10 KiB
C#
Raw Normal View History

2016-11-04 09:31:05 +01:00
using System;
2016-10-30 00:22:20 +02:00
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security;
2017-02-05 21:44:08 +01:00
using System.Threading;
2016-10-30 00:22:20 +02:00
using System.Threading.Tasks;
2016-11-08 19:44:23 +01:00
using Emby.Common.Implementations.Networking;
2016-11-04 09:31:05 +01:00
using MediaBrowser.Model.Net;
2016-10-30 00:22:20 +02:00
2016-11-04 09:31:05 +01:00
namespace Emby.Common.Implementations.Net
2016-10-30 00:22:20 +02: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 21:50:09 +01:00
internal sealed class UdpSocket : DisposableManagedObjectBase, ISocket
2016-10-30 00:22:20 +02:00
{
2016-11-04 20:51:59 +01:00
private Socket _Socket;
2016-10-30 00:22:20 +02:00
private int _LocalPort;
2017-03-26 18:26:52 +02:00
2017-03-26 21:00:35 +02:00
private readonly SocketAsyncEventArgs _receiveSocketAsyncEventArgs = new SocketAsyncEventArgs()
{
SocketFlags = SocketFlags.None
};
private readonly SocketAsyncEventArgs _sendSocketAsyncEventArgs = new SocketAsyncEventArgs()
2017-03-26 18:26:52 +02:00
{
SocketFlags = SocketFlags.None
};
private TaskCompletionSource<SocketReceiveResult> _currentReceiveTaskCompletionSource;
2017-03-26 21:00:35 +02:00
private TaskCompletionSource<int> _currentSendTaskCompletionSource;
private readonly SemaphoreSlim _sendLock = new SemaphoreSlim(1, 1);
2016-10-30 00:22:20 +02:00
2016-11-04 20:51:59 +01:00
public UdpSocket(Socket socket, int localPort, IPAddress ip)
2016-10-30 00:22:20 +02:00
{
if (socket == null) throw new ArgumentNullException("socket");
_Socket = socket;
_LocalPort = localPort;
2016-12-04 22:30:38 +01:00
LocalIPAddress = NetworkManager.ToIpAddressInfo(ip);
2016-10-30 00:22:20 +02:00
_Socket.Bind(new IPEndPoint(ip, _LocalPort));
2017-03-26 18:26:52 +02:00
InitReceiveSocketAsyncEventArgs();
}
private void InitReceiveSocketAsyncEventArgs()
{
2017-03-28 19:32:24 +02:00
var receiveBuffer = new byte[8192];
2017-03-26 21:00:35 +02:00
_receiveSocketAsyncEventArgs.SetBuffer(receiveBuffer, 0, receiveBuffer.Length);
2017-03-26 18:26:52 +02:00
_receiveSocketAsyncEventArgs.Completed += _receiveSocketAsyncEventArgs_Completed;
2017-03-26 21:00:35 +02:00
var sendBuffer = new byte[8192];
_sendSocketAsyncEventArgs.SetBuffer(sendBuffer, 0, sendBuffer.Length);
_sendSocketAsyncEventArgs.Completed += _sendSocketAsyncEventArgs_Completed;
2017-03-26 18:26:52 +02:00
}
private void _receiveSocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)
{
var tcs = _currentReceiveTaskCompletionSource;
if (tcs != null)
{
_currentReceiveTaskCompletionSource = null;
2017-03-26 21:00:35 +02:00
if (e.SocketError == SocketError.Success)
2017-03-26 18:26:52 +02:00
{
2017-03-26 21:00:35 +02: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 18:26:52 +02:00
}
2016-10-30 00:22:20 +02:00
}
2017-03-02 21:50:09 +01:00
public UdpSocket(Socket socket, IpEndPointInfo endPoint)
{
if (socket == null) throw new ArgumentNullException("socket");
_Socket = socket;
_Socket.Connect(NetworkManager.ToIPEndPoint(endPoint));
2017-03-26 18:26:52 +02:00
InitReceiveSocketAsyncEventArgs();
2017-03-02 21:50:09 +01:00
}
2016-10-30 00:22:20 +02:00
2016-12-04 22:30:38 +01:00
public IpAddressInfo LocalIPAddress
{
get;
private set;
}
2017-03-02 21:50:09 +01:00
public Task<SocketReceiveResult> ReceiveAsync(CancellationToken cancellationToken)
2016-10-30 00:22:20 +02:00
{
ThrowIfDisposed();
2016-11-04 19:56:47 +01:00
var tcs = new TaskCompletionSource<SocketReceiveResult>();
2016-11-04 20:51:59 +01:00
EndPoint receivedFromEndPoint = new IPEndPoint(IPAddress.Any, 0);
2017-03-27 01:53:50 +02:00
var state = new AsyncReceiveState(_Socket, receivedFromEndPoint);
state.TaskCompletionSource = tcs;
2017-03-13 05:49:10 +01:00
cancellationToken.Register(() => tcs.TrySetCanceled());
2017-03-26 18:26:52 +02:00
_receiveSocketAsyncEventArgs.RemoteEndPoint = receivedFromEndPoint;
_currentReceiveTaskCompletionSource = tcs;
2017-03-27 01:36:52 +02:00
try
{
var willRaiseEvent = _Socket.ReceiveFromAsync(_receiveSocketAsyncEventArgs);
2017-03-26 21:00:35 +02:00
2017-03-27 01:36:52 +02:00
if (!willRaiseEvent)
{
_receiveSocketAsyncEventArgs_Completed(this, _receiveSocketAsyncEventArgs);
}
}
catch (Exception ex)
2017-03-26 21:00:35 +02:00
{
2017-03-27 01:36:52 +02:00
tcs.TrySetException(ex);
2017-03-26 21:00:35 +02:00
}
2016-10-30 00:22:20 +02:00
return tcs.Task;
}
2017-02-05 21:44:08 +01:00
public Task SendAsync(byte[] buffer, int size, IpEndPointInfo endPoint, CancellationToken cancellationToken)
2016-10-30 00:22:20 +02:00
{
ThrowIfDisposed();
2016-11-04 19:56:47 +01:00
if (buffer == null) throw new ArgumentNullException("messageData");
2016-10-30 00:22:20 +02:00
if (endPoint == null) throw new ArgumentNullException("endPoint");
2017-03-26 21:54:50 +02:00
var ipEndPoint = NetworkManager.ToIPEndPoint(endPoint);
2017-03-26 21:00:35 +02:00
2017-03-26 21:54:50 +02:00
#if NETSTANDARD1_6
2017-03-26 21:00:35 +02:00
2017-03-26 21:54:50 +02:00
if (size != buffer.Length)
{
byte[] copy = new byte[size];
Buffer.BlockCopy(buffer, 0, copy, 0, size);
buffer = copy;
}
2017-03-26 21:00:35 +02:00
2017-03-26 21:54:50 +02:00
cancellationToken.ThrowIfCancellationRequested();
2016-12-04 22:30:38 +01:00
2017-03-26 21:54:50 +02:00
_Socket.SendTo(buffer, ipEndPoint);
return Task.FromResult(true);
#else
var taskSource = new TaskCompletionSource<bool>();
2016-11-04 19:56:47 +01:00
2017-03-26 21:54:50 +02:00
try
{
_Socket.BeginSendTo(buffer, 0, size, SocketFlags.None, ipEndPoint, result =>
{
if (cancellationToken.IsCancellationRequested)
{
taskSource.TrySetCanceled();
return;
}
try
{
_Socket.EndSend(result);
taskSource.TrySetResult(true);
}
catch (Exception ex)
{
taskSource.TrySetException(ex);
}
}, null);
}
catch (Exception ex)
2016-11-04 19:56:47 +01:00
{
2017-03-26 21:54:50 +02:00
taskSource.TrySetException(ex);
2016-11-04 19:56:47 +01:00
}
2017-03-26 21:54:50 +02:00
return taskSource.Task;
#endif
//ThrowIfDisposed();
//if (buffer == null) throw new ArgumentNullException("messageData");
//if (endPoint == null) throw new ArgumentNullException("endPoint");
//cancellationToken.ThrowIfCancellationRequested();
//var tcs = new TaskCompletionSource<int>();
//cancellationToken.Register(() => tcs.TrySetCanceled());
//_sendSocketAsyncEventArgs.SetBuffer(buffer, 0, size);
//_sendSocketAsyncEventArgs.RemoteEndPoint = NetworkManager.ToIPEndPoint(endPoint);
//_currentSendTaskCompletionSource = tcs;
//var willRaiseEvent = _Socket.SendAsync(_sendSocketAsyncEventArgs);
//if (!willRaiseEvent)
//{
// _sendSocketAsyncEventArgs_Completed(this, _sendSocketAsyncEventArgs);
//}
//return tcs.Task;
2017-03-26 21:00:35 +02:00
}
public async Task SendWithLockAsync(byte[] buffer, int size, IpEndPointInfo endPoint, CancellationToken cancellationToken)
{
ThrowIfDisposed();
2017-02-05 21:44:08 +01:00
2017-03-26 21:54:50 +02:00
//await _sendLock.WaitAsync(cancellationToken).ConfigureAwait(false);
2016-10-30 00:22:20 +02:00
try
{
2017-03-26 21:00:35 +02:00
await SendAsync(buffer, size, endPoint, cancellationToken).ConfigureAwait(false);
2016-10-30 00:22:20 +02:00
}
2017-03-26 21:00:35 +02:00
finally
2016-10-30 00:22:20 +02:00
{
2017-03-26 21:54:50 +02:00
//_sendLock.Release();
2016-10-30 00:22:20 +02:00
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
var socket = _Socket;
if (socket != null)
socket.Dispose();
2017-03-26 21:00:35 +02:00
_sendLock.Dispose();
2016-10-30 00:22:20 +02:00
2017-03-26 21:00:35 +02:00
var tcs = _currentReceiveTaskCompletionSource;
if (tcs != null)
{
tcs.TrySetCanceled();
}
var sendTcs = _currentSendTaskCompletionSource;
if (sendTcs != null)
{
sendTcs.TrySetCanceled();
}
2016-10-30 00:22:20 +02:00
}
}
2016-11-04 09:31:05 +01:00
private static IpEndPointInfo ToIpEndPointInfo(IPEndPoint endpoint)
{
if (endpoint == null)
{
return null;
}
2016-11-11 08:24:36 +01:00
return NetworkManager.ToIpEndPointInfo(endpoint);
2016-11-04 09:31:05 +01:00
}
2017-03-27 01:53:50 +02:00
private void ProcessResponse(IAsyncResult asyncResult)
{
#if NET46
var state = asyncResult.AsyncState as AsyncReceiveState;
try
{
var bytesRead = state.Socket.EndReceiveFrom(asyncResult, ref state.RemoteEndPoint);
var ipEndPoint = state.RemoteEndPoint as IPEndPoint;
state.TaskCompletionSource.SetResult(
new SocketReceiveResult
{
Buffer = state.Buffer,
ReceivedBytes = bytesRead,
RemoteEndPoint = ToIpEndPointInfo(ipEndPoint),
LocalIPAddress = LocalIPAddress
}
);
}
catch (ObjectDisposedException)
{
state.TaskCompletionSource.SetCanceled();
}
catch (Exception ex)
{
state.TaskCompletionSource.SetException(ex);
}
#endif
}
private class AsyncReceiveState
{
public AsyncReceiveState(Socket socket, EndPoint remoteEndPoint)
{
this.Socket = socket;
this.RemoteEndPoint = remoteEndPoint;
}
public EndPoint RemoteEndPoint;
public byte[] Buffer = new byte[8192];
public Socket Socket { get; private set; }
public TaskCompletionSource<SocketReceiveResult> TaskCompletionSource { get; set; }
}
2016-10-30 00:22:20 +02:00
}
2016-11-04 09:31:05 +01:00
}