From 7054077cff8fc1173c0242ffc6d56728bca29c6e Mon Sep 17 00:00:00 2001 From: Josip Habjan Date: Wed, 25 Sep 2019 15:05:32 +0100 Subject: [PATCH] ConnectAsync implementation fix for Ubuntu 18.04 ConnectAsync was not implemented properly and as result, callback (Complete event) was never triggered (on Ubuntu) when called from sync code and code never got to the handshake point. ConnectAsync returns boolean (true if the I/O operation is pending. The Completed event on the e parameter will be raised upon completion of the operation, false if the I/O operation completed synchronously. In this case, The Completed event on the e parameter will not be raised and the e object passed as a parameter may be examined immediately after the method call returns to retrieve the result of the operation.) --- Common/ConnectAsyncExtension.Net45.cs | 51 ++++++++++++--------------- 1 file changed, 22 insertions(+), 29 deletions(-) diff --git a/Common/ConnectAsyncExtension.Net45.cs b/Common/ConnectAsyncExtension.Net45.cs index 7fedd3e..c9531a7 100644 --- a/Common/ConnectAsyncExtension.Net45.cs +++ b/Common/ConnectAsyncExtension.Net45.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; @@ -16,51 +16,44 @@ internal static bool PreferIPv4Stack() public static void ConnectAsync(this EndPoint remoteEndPoint, EndPoint localEndPoint, ConnectedCallback callback, object state) { var e = CreateSocketAsyncEventArgs(remoteEndPoint, callback, state); - + #if NETSTANDARD + AddressFamily addressFamily = remoteEndPoint.AddressFamily; + if (localEndPoint != null) { - var socket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); + addressFamily = localEndPoint.AddressFamily; + } - try - { - socket.ExclusiveAddressUse = false; - socket.Bind(localEndPoint); - } - catch (Exception exc) - { - callback(null, state, null, exc); - return; - } + var socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp); - socket.ConnectAsync(e); - } - else - { - Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, e); - } #else var socket = PreferIPv4Stack() - ? new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) + ? new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) : new Socket(SocketType.Stream, ProtocolType.Tcp); - - if (localEndPoint != null) +#endif + + try { - try + if (localEndPoint != null) { socket.ExclusiveAddressUse = false; socket.Bind(localEndPoint); } - catch (Exception exc) + + bool wasAsync = socket.ConnectAsync(e); + + if (!wasAsync) { - callback(null, state, null, exc); - return; + callback(socket, state, e, null); } } - - socket.ConnectAsync(e); -#endif + catch (Exception exc) + { + callback(null, state, null, exc); + } + } } }