Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Wrapper for sockets-for-pcl UdpSocketReceiver that provides a blocking `Receive` call
public class BetterUdpSocket : IDisposable
{
private BlockingCollection<byte[]> _readBuffer;
private readonly UdpSocketReceiver _backingUdpSocketReceiver = new UdpSocketReceiver();
public BetterUdpSocket()
{
_backingUdpSocketReceiver.MessageReceived += OnMessageReceived;
}
public Task StartListeningAsync(int port, ICommsInterface listenOn)
{
_readBuffer = new BlockingCollection<byte[]>();
return _backingUdpSocketReceiver.StartListeningAsync(port, listenOn);
}
public Task StopListeningAsync()
{
return _backingUdpSocketReceiver.StopListeningAsync()
.ContinueWith(_ => _readBuffer == null);
}
private void OnMessageReceived(object sender, UdpSocketMessageReceivedEventArgs args)
{
var bytes = args.ByteData;
_readBuffer.Add(bytes);
}
public Task<byte[]> ReceiveAsync(CancellationToken cancellationToken = default(CancellationToken))
{
if (_readBuffer == null)
throw new InvalidOperationException("The socket must be listening in order to receive data.");
return Task.Run(() => _readBuffer.Take(), cancellationToken);
}
public Task SendToAsync(byte[] data, string address, int port)
{
return _backingUdpSocketReceiver.SendToAsync(data, address, port);
}
public void Dispose()
{
if (_backingUdpSocketReceiver != null)
_backingUdpSocketReceiver.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment