コード例 #1
0
ファイル: ConnectionListener.cs プロジェクト: rflechner/swan
        /// <summary>
        /// Continuously checks for client connections until the Close method has been called.
        /// </summary>
        /// <returns>A task that represents the asynchronous connection operation</returns>
        private async Task DoWorkAsync()
        {
            _cancellationPending = false;
            _listenerSocket      = new TcpListener(LocalEndPoint);
            _listenerSocket.Start();
            _cancelListening = new CancellationTokenSource();

            try
            {
                while (_cancellationPending == false)
                {
                    try
                    {
                        var client = await Task.Run(() => _listenerSocket.AcceptTcpClientAsync(), _cancelListening.Token);

                        var acceptingArgs = new ConnectionAcceptingEventArgs(client);
                        OnConnectionAccepting(this, acceptingArgs);

                        if (acceptingArgs.Cancel)
                        {
#if !NET452
                            client.Dispose();
#else
                            client.Close();
#endif
                            continue;
                        }

                        OnConnectionAccepted(this, new ConnectionAcceptedEventArgs(client));
                    }
                    catch (Exception ex)
                    {
                        OnConnectionFailure(this, new ConnectionFailureEventArgs(ex));
                    }
                }

                OnListenerStopped(this, new ConnectionListenerStoppedEventArgs(LocalEndPoint));
            }
            catch (ObjectDisposedException)
            {
                OnListenerStopped(this, new ConnectionListenerStoppedEventArgs(LocalEndPoint));
            }
            catch (Exception ex)
            {
                OnListenerStopped(this,
                                  new ConnectionListenerStoppedEventArgs(LocalEndPoint, _cancellationPending ? null : ex));
            }
            finally
            {
                _backgroundWorkerTask = null;
                _cancellationPending  = false;
            }
        }
コード例 #2
0
 private static void DeviceFinder_DeviceConnectionAccepting(object sender, ConnectionAcceptingEventArgs e)
 {
     e.ConnectionDeferral.AcceptAlways();
 }