Skip to content

Instantly share code, notes, and snippets.

@alanmcgovern
Last active May 9, 2016 00:46
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 alanmcgovern/8bbf6eb4a8e73539e350f40194bc381b to your computer and use it in GitHub Desktop.
Save alanmcgovern/8bbf6eb4a8e73539e350f40194bc381b to your computer and use it in GitHub Desktop.
public async Task BeginListeningAsync (CancellationToken token)
{
var tcpListener = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var tcp6Listener = new Socket (AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
using (tcpListener)
using (tcp6Listener) {
tcpListener.Bind (new IPEndPoint (IPAddress.Any, ListenPort));
tcp6Listener.Bind (new IPEndPoint (IPAddress.IPv6Any, ListenPort));
await Task.WhenAll (
BeginListeningAsync (tcp6Listener, token),
BeginListeningAsync (tcpListener, token)
).ConfigureAwait (false);
}
}
async Task BeginListeningAsync (Socket listener, CancellationToken token)
{
try {
listener.Listen (10);
using (token.Register (() => listener.Dispose ())) {
while (!token.IsCancellationRequested) {
var socket = await Task.Factory.FromAsync (listener.BeginAccept (null, null), listener.EndAccept).ConfigureAwait (false);
ContextReceived (Catalog, socket, token);
}
}
} catch (ObjectDisposedException ex) {
if (!token.IsCancellationRequested) {
Console.WriteLine (ex, "Unexpected ObjectDisposedException in BeginListeningAsync");
throw;
}
} catch (OperationCanceledException) {
// We cancelled successfully
} catch (Exception ex) {
Console.WriteLine (ex, string.Format ("Unhandled exception in BeginListeningAsync. {0}", listener.AddressFamily));
}
}
static async void ContextReceived (Catalog catalog, Socket socket, CancellationToken token)
{
try {
using (socket)
Console.WriteLine ("Just disposing the socket");
} catch (Exception ex) {
socket.Close ();
Console.WriteLine (ex, "The connection died. Oops!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment