Last active
February 11, 2021 12:39
-
-
Save antonfirsov/e86ddc9ac287b7dd63cd85f78ca125f6 to your computer and use it in GitHub Desktop.
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
// The workaround is utilizing ConnectCallback, which is a .NET 5+ feature. | |
// For more info see: | |
// https://devblogs.microsoft.com/dotnet/net-5-new-networking-improvements/#socketshttphandler-extension-points | |
public HttpClient CreateHttpClientWithReusePort() | |
{ | |
SocketsHttpHandler handler = new SocketsHttpHandler | |
{ | |
ConnectCallback = ReusePortConnectAsync | |
}; | |
return new HttpClient(handler); | |
static async ValueTask<Stream> ReusePortConnectAsync(SocketsHttpConnectionContext context, CancellationToken cancellationToken) | |
{ | |
// Default socket creation logic | |
Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp); | |
socket.NoDelay = true; | |
// Enable SO_REUSE_UNICASTPORT: | |
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort, 1); | |
try | |
{ | |
await socket.ConnectAsync(context.DnsEndPoint, cancellationToken).ConfigureAwait(false); | |
return new NetworkStream(socket, ownsSocket: true); | |
} | |
catch | |
{ | |
socket.Dispose(); | |
throw; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment