Esempio n. 1
0
        public async Task<ConnectResult> TryConnectAsync(AsyncTcpConnector connector, int milliseconds)
        {
            var result = new ConnectResult { TimerTask = Task.Delay(milliseconds, Token) };

            try
            {
                task = connector.ConnectAsync(tcp);
                if (task == await Task.WhenAny(task, result.TimerTask).ConfigureAwait(false))
                {
                    await task;
                    stream = tcp.GetStream();
                    result.Connected = true;
                }
            }
            catch (SocketException)
            {
                // ignore
            }

            return result;
        }
Esempio n. 2
0
        static void Main(string[] args)
        {
            try
            {
                string address = args[0];
                int port = int.Parse(args[1]);

                var cts = new CancellationTokenSource();
                Task.Run(() => { Console.ReadLine(); cts.Cancel(); });

                var loop = new AsyncTcpLoopImpl();
                var connector = new AsyncTcpConnector(address, port);
                loop.RunAsync(connector, 2000, cts.Token).Wait();
            }
            catch (AggregateException e)
            {
                e.Handle(x => { Console.WriteLine(x); return true; });
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Esempio n. 3
0
        private async Task InternalRunAsync(AsyncTcpConnector connector, int connectTimeout, CancellationToken ct)
        {
            while (!ct.IsCancellationRequested)
            {
                OnConnecting();
                Task timerTask = null;

                using (var tcp = new AsyncTcpClient(ct))
                {
                    var cr = await tcp.TryConnectAsync(connector, connectTimeout);
                    timerTask = cr.TimerTask;

                    if (cr.Connected)
                    {
                        try
                        {
                            await OnConnected(tcp);
                        }
                        catch (IOException e)
                        {
                            if (!(e.InnerException is SocketException)) throw;
                        }
                        catch (OperationCanceledException)
                        {
                        }
                    }
                }

                try
                {
                    await timerTask;
                }
                catch (OperationCanceledException)
                {
                }
            }
        }
Esempio n. 4
0
 public Task RunAsync(AsyncTcpConnector connector, int connectTimeout, CancellationToken ct)
 {
     return Task.Run(() => InternalRunAsync(connector, connectTimeout, ct));
 }