Skip to content

Instantly share code, notes, and snippets.

@rdavisau
Created April 20, 2015 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rdavisau/72052d6d86d983035130 to your computer and use it in GitHub Desktop.
Save rdavisau/72052d6d86d983035130 to your computer and use it in GitHub Desktop.
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