-
-
Save alanmcgovern/8bbf6eb4a8e73539e350f40194bc381b to your computer and use it in GitHub Desktop.
This file contains 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 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