using Bts.Net; using System.Net.Sockets; using System.Net; using BCG; using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Threading; using System.Reflection.Metadata.Ecma335; using System.Diagnostics.CodeAnalysis; namespace bts { // Unlike AsyncTCPConnectionAcceptor_APM this class is static since the requests to connect are stand alone requests // whereas AsyncTCPConnectionAcceptor_APM is always listening for incoming connections which lends itself to more // statefullness and hence non static public static class AsyncTCPConnector_AsyncWrapper { public static void connect_to(RemoteConnectionInfo server_address, ITCPConnectionHandler handler) { bts.Log.Gen.info($"AsyncTCPConnector_AsyncWrapper.connect_to server: {server_address}"); //Task.Run(() => _connect_to(server_address, handler)); ThreadPool.QueueUserWorkItem(_ => _keep_trying_blocking_function( Connect, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5))); bool Connect() { try { return _connect_to(server_address, handler); } catch (Exception ex) { Log.assert(false, $"AsyncTCPConnector_AsyncWrapper connect threw exception: {ex}"); } return false; } } // this is the actual fuction thta calls TCPCLient sync methof and establishes a connection private static bool _connect_to(RemoteConnectionInfo server_rci, ITCPConnectionHandler handler) { // TODO, random sleep bts.Log.Gen.info($"AsyncTCPConnector_AsyncWrapper._connect_to server: {server_rci}"); if (!CreateTcpClient(out var tcp_client)) { return false; } bts.Log.Gen.info($"AsyncTCPConnector_AsyncWrapper._connect_to server new TcpClient returned, connected: {tcp_client.Connected}"); ITCPConnection conn = _create_connection(tcp_client); var conn_rci = conn.get_peer_address(); bts.Log.Gen.info($"AsyncTCPConnector_AsyncWrapper._connect_to new connection, server_rci: {server_rci} connection.peer_address: {conn_rci}"); Log.assert(HostComparer.Equals(server_rci.ip, conn_rci.ip), $"{server_rci}!={conn_rci}"); bts.Log.Gen.info($"AsyncTCPConnector_AsyncWrapper._connect_to new connection, self: {conn.get_self_address()} peer: {conn.get_peer_address()}, calling onConnection now"); handler.onConnection(conn); return true; bool CreateTcpClient([NotNullWhen(true)]out TcpClient? tcpClient) { try { tcpClient = new(server_rci.ip, server_rci.port); return true; } catch (SocketException ex) { Log.Gen.warn($"Failed to connect. server_rci: {server_rci} Exception:\n{ex}"); } tcpClient = null; return false; } } private static ITCPConnection _create_connection(TcpClient tcp_client) { ITCPConnection conn = new AsyncTCPConnection_AsyncWrapper(tcp_client); // ITCPConnection conn = new AsyncTCPConnection_APM(tcp_client.GetStream().Socket, TimeSpan.FromSeconds(1), ITCPConnection.ConnectionSide.Client); return conn; } // this is a ganeric function that calls a sync action function, and if unsuccessful timesout after "timeout" // wais for wait_before_retrying before trying again public static void _keep_trying_blocking_function(Func action, TimeSpan timeout, TimeSpan wait_before_retrying) { Func try_once = () => { var task = Task.Run(action); return Task.WhenAny(task, Task.Delay(timeout)).GetAwaiter().GetResult() == task && task.IsCompletedSuccessfully && task.Result; }; bool connected = false; while (!connected) { connected = try_once(); System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1)); } } } }