Created
April 20, 2015 10:15
-
-
Save rdavisau/72052d6d86d983035130 to your computer and use it in GitHub Desktop.
Wrapper for sockets-for-pcl UdpSocketReceiver that provides a blocking `Receive` call
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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