Esempio n. 1
0
        private void InitSocket()
        {
            Exec(Request.Create(RequestCommand.Use).AppendArgument(DEFAULT_TUBE).ExpectStatuses(ResponseStatus.Using));
            var client = ((IWatchedTubeClient)this);
            var tubes  = new HashSet <string>();

            foreach (var tube in client.ListWatchedTubes())
            {
                tubes.Add(tube);
            }
            if (tubes.Contains(DEFAULT_TUBE))
            {
                tubes.Remove(DEFAULT_TUBE);
            }
            else
            {
                client.Watch(DEFAULT_TUBE);
            }
            var watched = 1;

            foreach (var tube in tubes)
            {
                watched = client.Ignore(tube);
            }
            if (watched != 1)
            {
                _socket.Dispose();
                throw new InitException();
            }
        }
Esempio n. 2
0
        public void Leave()
        {
            if (!_isJoined)
            {
                return;
            }

            _processor.Stop();
            var keys = _processor.Get(_processor.KeyCount);

            // Do this before instantiating leaver since it uses the same socket
            _group.OnReceiveMessage -= _group_OnReceiveMessage;

            // If we're the only node, there is no need to redistribute keys
            if (_nodeCount > 1)
            {
                using (var _leaver = new Leaver(_config, _group, keys))
                    _leaver.Leave();
            }

            // Kill socket so we don't respond to group messages
            _group.Dispose();

            _isJoined = false;

            LogBroker.Log(string.Format("{0} keys processed", _processor.ProcessedKeyCount));
            LogBroker.Log("Leave Complete");
        }
Esempio n. 3
0
 public void Dispose()
 {
     if (_socket != null)
     {
         _socket.Dispose();
         _socket = null;
     }
 }
Esempio n. 4
0
        /// <summary>
        /// Causes the server to stop listening for multicast messages, being SSDP search requests and notifications.
        /// </summary>
        /// <exception cref="System.ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception>
        public void StopListeningForBroadcasts()
        {
            ThrowIfDisposed();

            lock (_BroadcastListenSocketSynchroniser)
            {
                if (_BroadcastListenSocket != null)
                {
                    _BroadcastListenSocket.Dispose();
                    _BroadcastListenSocket = null;
                }
            }
        }
Esempio n. 5
0
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (Interlocked.Exchange(ref _state, 1) == 0)
         {
             try
             {
                 _socket.Shutdown(SocketShutdown.Both);
             }
             catch { }
         }
         if (Interlocked.Exchange(ref _state, 2) == 1)
         {
             try
             {
                 _socket.Close(100);
             }
             catch { }
         }
         if (Interlocked.Exchange(ref _state, 3) == 2)
         {
             try
             {
                 _socket.Dispose();
             }
             catch { }
         }
     }
     base.Dispose(disposing);
 }
Esempio n. 6
0
        internal void Dispose()
        {
            LoggedIn = false;

            socket.Dispose();
            socket = null;

            guid      = Guid.Empty;
            name      = null;
            orgname   = null;
            version   = null;
            region    = null;
            message   = null;
            avatar    = null;
            orgavatar = null;
            localip   = null;
            nodeip    = null;

            counters.Clear();
            counters = null;

            ignored.Clear();
            ignored = null;

            extended_props.Clear();
            extended_props = null;
        }
Esempio n. 7
0
 public void Dispose()
 {
     _disposed = true;
     if (_socket != null)
     {
         _socket.Dispose();
     }
 }
Esempio n. 8
0
 private void CloseInternal()
 {
     _isDisposed = true;
     RecordOpenCloseInfo("Tunnel closed");
     _socket.Close();
     _socket.Dispose();
     Closed?.Invoke();
 }
Esempio n. 9
0
        /// <summary>
        /// Stops this instance.
        /// </summary>
        public void Stop()
        {
            _isDisposed = true;

            if (_udpClient != null)
            {
                _udpClient.Dispose();
            }
        }
Esempio n. 10
0
        public void Shutdown()
        {
            IsAlive = false;

            if (socket != null)
            {
                socket.Dispose();
                //socket = null;
            }
        }
Esempio n. 11
0
 public void TearDown()
 {
     if (stopListening != null)
     {
         stopListening.Dispose();
     }
     wh.Dispose();
     server.Dispose();
     client.Dispose();
 }
Esempio n. 12
0
 protected override void Dispose(bool disposing)
 {
     if (m_isConnected)
     {
         m_socket.Disconnect(false);
     }
     m_isConnected  = false;
     m_isConnecting = false;
     m_socket.Dispose();
 }
Esempio n. 13
0
        internal static async Task SimplePubSub(SocketConfiguration configuration)
        {
            ISocket socket = ToSocket(configuration);

            socket.RegisterSubscriber <PubSubMessage>(msg => System.Console.WriteLine("msg received: " + msg.Message));
            await socket.PublishAsync(new PubSubMessage { Message = "Published simply" });

            Console.ReadLine();

            socket.Dispose();
        }
Esempio n. 14
0
        public virtual void OnClose(ISocket socket)
        {
            Debug.WriteLine("Socket OnClose.");

            socket.Dispose();

            // release (indirect) reference to socket
            transactionDelegateSubscription.Dispose();
            transactionDelegateSubscription = null;

            // XXX return self to freelist
        }
Esempio n. 15
0
        protected override void OnDispose(bool disposing)
        {
            base.OnDispose(disposing);

            var host = _Host;

            // 如果是已连接的会话,可以销毁
            if (host != null && Connected)
            {
                _Host.Dispose();
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool dispose)
        {
            if (dispose)
            {
                _isDisposed = true;

                if (_udpClient != null)
                {
                    _udpClient.Dispose();
                }
            }
        }
 private void Reclaim(ISocket socket)
 {
     if (_disposed)
     {
         socket.Dispose();
         return;
     }
     lock (_availableSockets) {
         if (!_busySockets.Remove(socket))
         {
             return;
         }
         if (!socket.Connected || _availableSockets.Count + _busySockets.Count >= MaxConnections)
         {
             // drop socket
             socket.Dispose();
             return;
         }
         _availableSockets.Enqueue(new Available(socket));
     }
 }
Esempio n. 18
0
 /// <summary>
 /// Causes the server to stop listening for multicast messages, being SSDP search requests and notifications.
 /// </summary>
 /// <exception cref="ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception>
 public void StopListeningForBroadcasts()
 {
     lock (_BroadcastListenSocketSynchroniser)
     {
         if (_BroadcastListenSocket != null)
         {
             _logger.LogInformation("{0} disposing _BroadcastListenSocket", GetType().Name);
             _BroadcastListenSocket.Dispose();
             _BroadcastListenSocket = null;
         }
     }
 }
Esempio n. 19
0
        public void OnClose(ISocket socket)
        {
            Debug.WriteLine("Socket OnClose.");

            socket.Dispose();

            // release (indirect) reference to socket
            transactionDelegateSubscription.Dispose();
            transactionDelegateSubscription = null;

            // XXX return self to freelist
        }
Esempio n. 20
0
        public void Send_ThrowsInterruptConnection_ShouldBeCaught()
        {
            var paramToSent = new byte[] { 0b01010101 };

            Mock.Arrange(() => _socket.Send(null)).IgnoreArguments().Throws(new SocketException(10054));
            _sut = new NetworkTunnel(_socket, _recorder);

            _sut.Send(paramToSent);

            Mock.Assert(() => _socket.Dispose(), Occurs.Exactly(1));
            Mock.Assert(() => _recorder.RecordInfo(Arg.AnyString, Arg.AnyString), Occurs.Exactly(3));
            Mock.Assert(() => _recorder.RecordError(Arg.AnyString, Arg.AnyString), Occurs.Never());
        }
Esempio n. 21
0
        public void Dispose()
        {
            if (_isDisposed)
            {
                return;
            }

            _listenerSocket?.Dispose();

            _cts.Dispose();

            _isDisposed = true;
        }
Esempio n. 22
0
        public ISocketDelegate OnConnection(IServer server, ISocket socket)
        {
            NumOnConnectionEvents++;

            if (OnConnectionAction != null)
            {
                return OnConnectionAction(server, socket);
            }
            else
            {
                socket.Dispose();
                return null;
            }
        }
Esempio n. 23
0
 public void Stop()
 {
     cancellationTokenSource.Cancel();
     heartBeating?.Dispose();
     inMessageQueue.CompleteAdding();
     outMessageQueue.CompleteAdding();
     receiving?.Wait(TerminationWaitTimeout);
     sending?.Wait(TerminationWaitTimeout);
     notifyListeners?.Wait(TerminationWaitTimeout);
     inMessageQueue.Dispose();
     outMessageQueue.Dispose();
     cancellationTokenSource.Dispose();
     intercomSocket?.Dispose();
 }
Esempio n. 24
0
        public ISocketDelegate OnConnection(IServer server, ISocket socket)
        {
            NumOnConnectionEvents++;

            if (OnConnectionAction != null)
            {
                return(OnConnectionAction(server, socket));
            }
            else
            {
                socket.Dispose();
                return(null);
            }
        }
Esempio n. 25
0
        public string LookupDotComDomain(string domainName, int port, string whoisServer,
                                         string whoisServerLookupQueryPrefix, int responseBufferSizeInBytes)
        {
            Guard.WhenArgument(domainName, "DomainName").IsNullOrEmpty().Throw();

            if (domainName.StartsWith(WhoisConstants.ForbiddenDomainStartSymbol))
            {
                throw new ArgumentException("Domain name cannot start with hyphen.");
            }

            if (!domainName.ToLower().EndsWith(WhoisConstants.DomainEndPattern))
            {
                throw new ArgumentException("Domain name should be a .com domain.");
            }

            var regex = new Regex(WhoisConstants.RegexDomainPattern);

            // remove ".com"
            if (!regex.IsMatch(domainName.ToLower().Substring(0, domainName.Length - 4)))
            {
                throw new ArgumentException("Domain should only contain letters, numbers or hyphen.");
            }

            Guard.WhenArgument(domainName.Length, "DomainName").IsLessThan(WhoisConstants.MinimumDomainNameLength).Throw();
            Guard.WhenArgument(domainName.Length, "DomainName").IsGreaterThan(WhoisConstants.MaximumDomainNameLength).Throw();

            Guard.WhenArgument(port, "Port").IsLessThan(WhoisConstants.TcpMinPort).Throw();
            Guard.WhenArgument(port, "Port").IsGreaterThan(WhoisConstants.TcpMaxPort).Throw();

            Guard.WhenArgument(whoisServer, "WhoisServer").IsNullOrEmpty().Throw();

            Guard.WhenArgument(whoisServerLookupQueryPrefix, "WhoisServerLookupQueryPrefix").IsNullOrEmpty().Throw();

            Guard.WhenArgument(responseBufferSizeInBytes, "ResponseBufferSizeInBytes").IsLessThan(WhoisConstants.MinimumResponseBufferSizeInBytes).Throw();
            Guard.WhenArgument(responseBufferSizeInBytes, "ResponseBufferSizeInBytes").IsGreaterThan(WhoisConstants.MaximumResponseBufferSizeInBytes).Throw();

            socket.Connect(whoisServer, port);

            byte[] query = Encoding.ASCII.GetBytes(whoisServerLookupQueryPrefix + domainName + Environment.NewLine);
            socket.Send(query);

            byte[] responseBytes = new byte[responseBufferSizeInBytes];
            socket.Receive(responseBytes);
            socket.Dispose();

            string humanReadableResponse = Encoding.UTF8.GetString(responseBytes);

            return(humanReadableResponse);
        }
Esempio n. 26
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }
            ISocket socket = this._socket;

            if (null == socket)
            {
                return;
            }
            this._socket = (ISocket)null;
            socket.Dispose();
        }
Esempio n. 27
0
 protected virtual void Dispose(bool suppressFinalizer)
 {
     if (_disposed)
     {
         return;
     }
     if (suppressFinalizer)
     {
         GC.SuppressFinalize(this);
     }
     if (_socket != null)
     {
         _socket.Dispose();
     }
     _disposed = true;
 }
Esempio n. 28
0
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            _disposed    = true;
            CurrentState = State.Stopped;

            // create a task which cleans up
            Task.Run(async() =>
            {
                // Dispose should not throw anything
                try
                {
                    // we are called from Dispose()
                    if (disposing)
                    {
                        if (null != _socket)
                        {
                            await _socket.DisconnectAsync();
                        }

                        if (null != _receivingTask)
                        {
                            await _receivingTask;
                            _receivingTask = null;
                        }

                        if (null != _socket)
                        {
                            _socket.Dispose();
                            _socket = null;
                        }

                        if (null != _serializer)
                        {
                            _serializer = null;
                        }
                    }
                }
                catch { }
            });
        }
Esempio n. 29
0
        internal static async Task PubSubWithCancellation(SocketConfiguration configuration)
        {
            ISocket socket = ToSocket(configuration);

            using var cts = new CancellationTokenSource();
            var token = cts.Token;

            socket.RegisterSubscriber <PubSubMessage>(msg => System.Console.WriteLine("msg received: " + msg.Message), token);
            cts.Cancel();
            System.Console.WriteLine("try multiple Publishes");
            foreach (var item in Enumerable.Range(0, 3))
            {
                await socket.PublishAsync(new PubSubMessage { Message = "Published with cancellation" });
            }
            System.Console.WriteLine("press any key to exit");
            Console.ReadLine();
            socket.Dispose();
        }
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            _disposed     = true;
            _currentState = States.Stopped;

            _disposingTask = Task.Run(async() =>
            {
                try
                {
                    if (null != _socket)
                    {
                        await _socket.DisconnectAsync();
                    }

                    if (null != _receivingTask)
                    {
                        await _receivingTask;
                        _receivingTask = null;
                    }

                    if (null != _socket)
                    {
                        _socket.Dispose();
                        _socket = null;
                    }

                    if (null != _serializer)
                    {
                        _serializer = null;
                    }
                }
                catch
                {
                }
            });

            GC.SuppressFinalize(this);
        }
Esempio n. 31
0
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: dispose managed state (managed objects)
                    _socketSubscription?.Dispose();
                    _socket.Stop();
                    _socket.Dispose();
                    _httpClient.Dispose();
                }

                // TODO: free unmanaged resources (unmanaged objects) and override finalizer
                // TODO: set large fields to null
                disposedValue = true;
            }
        }
Esempio n. 32
0
        public bool Close()
        {
            bool rt = false;
            int  errorCode = 0; string errorMsg = "关闭成功";

            try
            {
                //若Socket已经打开,则关闭
                if (ISocket != null && ISocket.Connected)
                {
                    ISocket.Shutdown(System.Net.Sockets.SocketShutdown.Both);
                    System.Threading.Thread.Sleep(100);
                    ISocket.Close();
                }
                rt = true;
            }
            catch (Exception ex)
            {
                errorCode = 1;
                errorMsg  = string.Format("服务器[{0}]{1}", ISocket.RemoteEndPoint, ex.Message);
                if (ClosedEvt != null)
                {
                    System.Windows.Forms.Control target = ClosedEvt.Target as System.Windows.Forms.Control;
                    errorCode = 1;
                    errorMsg  = string.Format("服务器[{0}]{1}", ISocket.RemoteEndPoint, errorMsg);
                    if (target != null && target.InvokeRequired)
                    {
                        //非创建控件线程同步调用事件:SocketClosed
                        target.Invoke(ClosedEvt, new object[] { errorCode, errorMsg });
                    }
                    else
                    {
                        //创建控件线程调用事件
                        ClosedEvt(SktProperty, errorCode, errorMsg);
                    }
                }
                ISocket.Dispose();
                ISocket = null;
            }
            finally { }
            return(rt);
        }
Esempio n. 33
0
        private void Reclaim(ISocket socket) {
            if(_disposed) {
                socket.Dispose();
                return;
            }
            lock(_availableSockets) {
                if(!_busySockets.Remove(socket)) {
                    return;
                }
                if(!socket.Connected || _availableSockets.Count + _busySockets.Count >= MaxConnections) {

                    // drop socket
                    socket.Dispose();
                    return;
                }
                _availableSockets.Enqueue(new Available(socket));
            }
        }
Esempio n. 34
0
        private void Reclaim(ISocket socket) {
            if(_disposed) {
                socket.Dispose();
                return;
            }
            lock(_syncroot) {
                if(!_busySockets.Remove(socket)) {
                    return;
                }
                if(socket.IsDisposed) {

                    // drop disposed sockets
                    socket.Dispose();
                    return;
                }

                // Try to hand the socket to the next client waiting in line
                if(_waitingQueue.ProvideSocket(socket)) {
                    return;
                }

                if(_availableSockets.Count + _busySockets.Count >= MaxConnections) {

                    // drop socket if we've already hit the max
                    socket.Dispose();
                    return;
                }

                // Add reclaimed socket to end of available list
                _availableSockets.Add(new Available(socket));
            }
        }