Skip to content
This repository was archived by the owner on Jul 28, 2020. It is now read-only.
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 22 additions & 29 deletions Common/ConnectAsyncExtension.Net45.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
Expand All @@ -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);
}

}
}
}