internal void InitConnect(IPEndPoint serverEndPoint,
                                  Action<IPEndPoint, Socket> onConnectionEstablished,
                                  Action<IPEndPoint, SocketError> onConnectionFailed,
                                  ITcpConnection connection,
                                  TimeSpan connectionTimeout)
        {
            if (serverEndPoint == null)
                throw new ArgumentNullException("serverEndPoint");
            if (onConnectionEstablished == null)
                throw new ArgumentNullException("onConnectionEstablished");
            if (onConnectionFailed == null)
                throw new ArgumentNullException("onConnectionFailed");

            var socketArgs = _connectSocketArgsPool.Get();
            var connectingSocket = new Socket(serverEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            socketArgs.RemoteEndPoint = serverEndPoint;
            socketArgs.AcceptSocket = connectingSocket;
            var callbacks = (CallbacksStateToken) socketArgs.UserToken;
            callbacks.OnConnectionEstablished = onConnectionEstablished;
            callbacks.OnConnectionFailed = onConnectionFailed;
            callbacks.PendingConnection = new PendingConnection(connection, DateTime.UtcNow.Add(connectionTimeout));

            AddToConnecting(callbacks.PendingConnection);

            try
            {
                var firedAsync = connectingSocket.ConnectAsync(socketArgs);
                if (!firedAsync)
                    ProcessConnect(socketArgs);
            }
            catch (ObjectDisposedException)
            {
                HandleBadConnect(socketArgs);
            }
        }
 private void OnConnectionClosed(ITcpConnection connection, SocketError socketError)
 {
     if (Interlocked.CompareExchange(ref _isClosed, 1, 0) == 0)
     {
         Console.WriteLine("Connection '{0}' [{1:B}] closed: {2}.", connection.ConnectionId, connection.RemoteEndPoint, socketError);
     }
 }
示例#3
0
 private void OnConnectionFailed(ITcpConnection connection, SocketError socketError)
 {
     if (Interlocked.CompareExchange(ref _isClosed, 1, 0) == 0)
     {
         Console.WriteLine("Connection '{0}' ({1:B}) to [{2}] failed: {3}.", _connectionName, _connectionId, connection.RemoteEndPoint, socketError);
     }
 }
示例#4
0
        private void HandleRemotingRequest(ITcpConnection connection, byte[] message, Action<byte[]> sendReplyAction)
        {
            var remotingRequest = RemotingUtil.ParseRequest(message);
            var requestHandlerContext = new SocketRequestHandlerContext(connection, sendReplyAction);

            IRequestHandler requestHandler;
            if (!_requestHandlerDict.TryGetValue(remotingRequest.Code, out requestHandler))
            {
                var errorMessage = string.Format("No request handler found for remoting request, request code:{0}", remotingRequest.Code);
                _logger.Error(errorMessage);
                requestHandlerContext.SendRemotingResponse(new RemotingResponse(-1, remotingRequest.Sequence, Encoding.UTF8.GetBytes(errorMessage)));
                return;
            }

            try
            {
                _logger.DebugFormat("Handling remoting request, request code:{0}, request sequence:{1}", remotingRequest.Code, remotingRequest.Sequence);
                var remotingResponse = requestHandler.HandleRequest(requestHandlerContext, remotingRequest);
                if (!remotingRequest.IsOneway && remotingResponse != null)
                {
                    requestHandlerContext.SendRemotingResponse(remotingResponse);
                }
            }
            catch (Exception ex)
            {
                var errorMessage = string.Format("Exception raised when handling remoting request, request code:{0}.", remotingRequest.Code);
                _logger.Error(errorMessage, ex);
                if (!remotingRequest.IsOneway)
                {
                    requestHandlerContext.SendRemotingResponse(new RemotingResponse(-1, remotingRequest.Sequence, Encoding.UTF8.GetBytes(ex.Message)));
                }
            }
        }
示例#5
0
 public void ReconnectToServer()
 {
     _connection.ConnectionClosed -= OnConnectionClosed;
     _connection = new TcpClientConnector().ConnectTo(Guid.NewGuid(), _localEndPoint, _serverEndPoint, OnConnectionEstablished, OnConnectionFailed);
     _connection.ConnectionClosed += OnConnectionClosed;
     _connection.ReceiveAsync(OnRawDataReceived);
 }
示例#6
0
 public void RegisterConsumer(string groupName, string consumerId, IEnumerable<string> subscriptionTopics, IEnumerable<string> consumingQueues, ITcpConnection connection)
 {
     var consumerGroup = _consumerGroupDict.GetOrAdd(groupName, key => new ConsumerGroup(key));
     consumerGroup.Register(consumerId, connection);
     consumerGroup.UpdateConsumerSubscriptionTopics(consumerId, subscriptionTopics);
     consumerGroup.UpdateConsumerConsumingQueues(consumerId, consumingQueues);
 }
示例#7
0
 public SocketClient()
 {
     var remoteEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), DEFAULT_PORT);
     var connector = new TcpClientConnector();
     _connection = connector.ConnectTo(_connectionId, remoteEndPoint, ConnectionTimeout, OnConnectionEstablished, OnConnectionFailed);
     _connection.ConnectionClosed += OnConnectionClosed;
     _connection.ReceiveAsync(OnRawDataReceived);
 }
示例#8
0
 public void Init(ITcpConnection connection, ICommandFactory commandFactory, int id, Car car)
 {
     Connection = connection;
     Id = id;
     Car = car;
     CommandFactory = commandFactory;
     _initilized = true;
 }
示例#9
0
        private void OnConnectionClosed(ITcpConnection connection, SocketError socketError)
        {
            connection.ConnectionClosed -= OnConnectionClosed;

            var handler = ConnectionClosed;
            if (handler != null)
                handler(this, socketError);
        }
 public SocketRequestHandlerContext(ITcpConnection connection, Action<byte[]> sendReplyAction)
 {
     Channel = new SocketChannel(connection);
     SendRemotingResponse = remotingResponse =>
     {
         sendReplyAction(RemotingUtil.BuildResponseMessage(remotingResponse));
     };
 }
示例#11
0
 public void Register(string consumerId, ITcpConnection connection)
 {
     var consumerHeartbeatInfo = _consumerDict.GetOrAdd(consumerId, key =>
     {
         _logger.InfoFormat("Consumer registered to group: {0}, consumerId: {1}", _groupName, consumerId);
         return new ConsumerHeartbeatInfo(key, connection);
     });
     consumerHeartbeatInfo.LastHeartbeatTime = DateTime.Now;
 }
示例#12
0
        private void HandleRemotingRequest(ITcpConnection connection, byte[] message, Action<byte[]> sendReplyAction)
        {
            if (_isShuttingdown) return;

            var remotingRequest = RemotingUtil.ParseRequest(message);
            var requestHandlerContext = new SocketRequestHandlerContext(connection, sendReplyAction);

            IRequestHandler requestHandler;
            if (!_requestHandlerDict.TryGetValue(remotingRequest.Code, out requestHandler))
            {
                var errorMessage = string.Format("No request handler found for remoting request:{0}", remotingRequest);
                _logger.Error(errorMessage);
                if (remotingRequest.Type != RemotingRequestType.Oneway)
                {
                    requestHandlerContext.SendRemotingResponse(new RemotingResponse(
                        remotingRequest.Type,
                        remotingRequest.Code,
                        remotingRequest.Sequence,
                        remotingRequest.CreatedTime,
                        -1,
                        Encoding.UTF8.GetBytes(errorMessage),
                        DateTime.Now,
                        remotingRequest.Header,
                        null));
                }
                return;
            }

            try
            {
                var remotingResponse = requestHandler.HandleRequest(requestHandlerContext, remotingRequest);
                if (remotingRequest.Type != RemotingRequestType.Oneway && remotingResponse != null)
                {
                    requestHandlerContext.SendRemotingResponse(remotingResponse);
                }
            }
            catch (Exception ex)
            {
                var errorMessage = string.Format("Unknown exception raised when handling remoting request:{0}.", remotingRequest);
                _logger.Error(errorMessage, ex);
                if (remotingRequest.Type != RemotingRequestType.Oneway)
                {
                    requestHandlerContext.SendRemotingResponse(new RemotingResponse(
                        remotingRequest.Type,
                        remotingRequest.Code,
                        remotingRequest.Sequence,
                        remotingRequest.CreatedTime,
                        -1,
                        Encoding.UTF8.GetBytes(ex.Message),
                        DateTime.Now,
                        remotingRequest.Header,
                        null));
                }
            }
        }
示例#13
0
 public void RegisterProducer(string producerId, ITcpConnection connection)
 {
     _producerDict.AddOrUpdate(producerId, key =>
     {
         _logger.InfoFormat("Producer registered, producerId: {0}", key);
         return new ProducerHeartbeatInfo(connection) { LastHeartbeatTime = DateTime.Now };
     }, (key, existing) =>
     {
         existing.LastHeartbeatTime = DateTime.Now;
         return existing;
     });
 }
示例#14
0
        public void RegisterBroker(ITcpConnection connection, BrokerRegistrationRequest request)
        {
            lock (_lockObj)
            {
                var brokerInfo = request.BrokerInfo;
                var cluster = _clusterDict.GetOrAdd(brokerInfo.ClusterName, x => new Cluster { ClusterName = x });
                var brokerGroup = cluster.BrokerGroups.GetOrAdd(brokerInfo.GroupName, x => new BrokerGroup { GroupName = x });
                Broker broker;
                if (!brokerGroup.Brokers.TryGetValue(brokerInfo.BrokerName, out broker))
                {
                    var connectionId = connection.RemotingEndPoint.ToAddress();
                    broker = new Broker
                    {
                        BrokerInfo = request.BrokerInfo,
                        TotalSendThroughput = request.TotalSendThroughput,
                        TotalConsumeThroughput = request.TotalConsumeThroughput,
                        TotalUnConsumedMessageCount = request.TotalUnConsumedMessageCount,
                        TopicQueueInfoList = request.TopicQueueInfoList,
                        TopicConsumeInfoList = request.TopicConsumeInfoList,
                        ProducerList = request.ProducerList,
                        ConsumerList = request.ConsumerList,
                        Connection = connection,
                        ConnectionId = connectionId,
                        LastActiveTime = DateTime.Now,
                        FirstRegisteredTime = DateTime.Now,
                        Group = brokerGroup
                    };
                    if (brokerGroup.Brokers.TryAdd(brokerInfo.BrokerName, broker))
                    {
                        _logger.InfoFormat("Registered new broker, brokerInfo: {0}", _jsonSerializer.Serialize(brokerInfo));
                    }
                }
                else
                {
                    broker.LastActiveTime = DateTime.Now;
                    broker.TotalSendThroughput = request.TotalSendThroughput;
                    broker.TotalConsumeThroughput = request.TotalConsumeThroughput;
                    broker.TotalUnConsumedMessageCount = request.TotalUnConsumedMessageCount;

                    if (!broker.BrokerInfo.IsEqualsWith(request.BrokerInfo))
                    {
                        var logInfo = string.Format("Broker basicInfo changed, old: {0}, new: {1}", broker.BrokerInfo, request.BrokerInfo);
                        broker.BrokerInfo = request.BrokerInfo;
                        _logger.Info(logInfo);
                    }

                    broker.TopicQueueInfoList = request.TopicQueueInfoList;
                    broker.TopicConsumeInfoList = request.TopicConsumeInfoList;
                    broker.ProducerList = request.ProducerList;
                    broker.ConsumerList = request.ConsumerList;
                }
            }
        }
        private void OnConnectionEstablished(ITcpConnection connection)
        {
            Log.Info("Connection '{connectionName}' ({connectionId:B}) to [{remoteEndPoint}] established.", ConnectionName, ConnectionId, connection.RemoteEndPoint);

            ScheduleHeartbeat(0);

            var handler = _connectionEstablished;

            if (handler != null)
            {
                handler(this);
            }
        }
 private void OnConnectionFailed(ITcpConnection connection, SocketError socketError)
 {
     if (Interlocked.CompareExchange(ref _isClosed, 1, 0) != 0)
     {
         return;
     }
     Log.Information("Connection '{connectionName}' ({connectionId:B}) to [{remoteEndPoint}] failed: {e}.",
                     ConnectionName, ConnectionId, connection.RemoteEndPoint, socketError);
     if (_connectionClosed != null)
     {
         _connectionClosed(this, socketError);
     }
 }
示例#17
0
 private void OnRawDataReceived(ITcpConnection connection, IEnumerable <ArraySegment <byte> > data)
 {
     try
     {
         _framer.UnFrameData(data);
     }
     catch (PackageFramingException ex)
     {
         _logger.Error("UnFrame data has exception.", ex);
         return;
     }
     connection.ReceiveAsync(OnRawDataReceived);
 }
示例#18
0
        private void HandleServerPushMessage(ITcpConnection connection, RemotingServerMessage message)
        {
            IRemotingServerMessageHandler messageHandler;

            if (_remotingServerMessageHandlerDict.TryGetValue(message.Code, out messageHandler))
            {
                messageHandler.HandleMessage(message);
            }
            else
            {
                _logger.ErrorFormat("No handler found for remoting server message:{0}", message);
            }
        }
        public AcceptedConnection(ITcpConnection connection)
        {
            _framer = new LengthPrefixMessageFramer();
            _framer.RegisterMessageArrivedCallback(OnMessageArrived);
            _connection = connection;

            _connection.ConnectionClosed += OnConnectionClosed;
            if (_connection.IsClosed)
            {
                OnConnectionClosed(_connection, SocketError.Success);
                return;
            }
        }
 private void OnConnectionClosed(ITcpConnection connection, SocketError socketError)
 {
     if (Interlocked.CompareExchange(ref _isClosed, 1, 0) != 0)
     {
         return;
     }
     Log.Info("Connection '{connectionName}{clientConnectionName}' [{remoteEndPoint}, {connectionId:B}] closed: {e}.",
              ConnectionName, ClientConnectionName.IsEmptyString() ? string.Empty : ":" + ClientConnectionName, connection.RemoteEndPoint, ConnectionId, socketError);
     if (_connectionClosed != null)
     {
         _connectionClosed(this, socketError);
     }
 }
 private void OnRawDataReceived(ITcpConnection connection, IEnumerable<ArraySegment<byte>> data)
 {
     try
     {
         _framer.UnFrameData(data);
     }
     catch (PackageFramingException exc)
     {
         Console.WriteLine(exc.Message);
         return;
     }
     connection.ReceiveAsync(OnRawDataReceived);
 }
示例#22
0
        public ChatView(Window mainWindow) : base(mainWindow)
        {
            this.mainWindow         = mainWindow;
            this.contactListManager = App.ServiceProvider.Get <ContactListManager>();
            this.profileViewModel   = App.ServiceProvider.Get <ProfileViewModel>();
            this.messageBoxService  = App.ServiceProvider.Get <IMessageBoxService>();
            this.clipboard          = App.ServiceProvider.Get <IClipboard>();

            this.messageThreadView     = new MessageThreadView(this.profileViewModel.Name, this.profileViewModel.ChatId, this.contactListManager.CurrentContact.Name, this.contactListManager.CurrentContact.ChatId);
            this.messagesViewModel     = new MessagesViewModel(App.ServiceProvider, this.contactListManager.CurrentContact.Id, this.messageThreadView);
            this.tcpConnection         = App.ServiceProvider.Get <ITcpConnection>();
            this.connectionListEntries = new List <string>();
            this.connectionListEntries.Add("Connecting...");
        }
示例#23
0
 private void OnConnectionEstablished(ITcpConnection connection)
 {
     foreach (var listener in _tcpConnectionEventListeners)
     {
         try
         {
             listener.OnConnectionEstablished(connection);
         }
         catch (Exception ex)
         {
             Log <ClientSocket> .Error(ex, string.Format("Client socket notify connection established has exception, name: {0}, listenerType: {1}", Name, listener.GetType().Name));
         }
     }
 }
示例#24
0
 private void OnConnectionEstablished(ITcpConnection connection)
 {
     foreach (var listener in _connectionEventListeners)
     {
         try
         {
             listener.OnConnectionEstablished(connection);
         }
         catch (Exception ex)
         {
             LogUtil.Error(string.Format("Notify connection established failed, listener type:{0}", listener.GetType().Name), ex);
         }
     }
 }
示例#25
0
        private void OnRawDataReceived(ITcpConnection connection, IEnumerable <ArraySegment <byte> > data)
        {
            try {
                _framer.UnFrameData(data);
            } catch (PackageFramingException exc) {
                _log.Error(exc, "TcpPackageConnection: [{0}, L{1}, {2:B}]. Invalid TCP frame received.", RemoteEndPoint,
                           LocalEndPoint, ConnectionId);
                Close("Invalid TCP frame received.");
                return;
            }

            //NOTE: important to be the last statement in the callback
            connection.ReceiveAsync(OnRawDataReceived);
        }
示例#26
0
        internal void InitConnect(IPEndPoint serverEndPoint,
                                  Action <Socket> onSocketAssigned,
                                  Action <IPEndPoint, Socket> onConnectionEstablished,
                                  Action <IPEndPoint, SocketError> onConnectionFailed,
                                  ITcpConnection connection,
                                  TimeSpan connectionTimeout)
        {
            if (serverEndPoint == null)
            {
                throw new ArgumentNullException("serverEndPoint");
            }
            if (onSocketAssigned == null)
            {
                throw new ArgumentNullException("onSocketAssigned");
            }
            if (onConnectionEstablished == null)
            {
                throw new ArgumentNullException("onConnectionEstablished");
            }
            if (onConnectionFailed == null)
            {
                throw new ArgumentNullException("onConnectionFailed");
            }

            var socketArgs       = _connectSocketArgsPool.Get();
            var connectingSocket = new Socket(serverEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            onSocketAssigned(connectingSocket);
            socketArgs.RemoteEndPoint = serverEndPoint;
            socketArgs.AcceptSocket   = connectingSocket;
            var callbacks = (CallbacksStateToken)socketArgs.UserToken;

            callbacks.OnConnectionEstablished = onConnectionEstablished;
            callbacks.OnConnectionFailed      = onConnectionFailed;
            callbacks.PendingConnection       = new PendingConnection(connection, DateTime.UtcNow.Add(connectionTimeout));

            AddToConnecting(callbacks.PendingConnection);

            try {
                var firedAsync = connectingSocket.ConnectAsync(socketArgs);
                if (!firedAsync)
                {
                    ProcessConnect(socketArgs);
                }
            } catch (ObjectDisposedException) {
                HandleBadConnect(socketArgs);
            } catch (Exception) {
                HandleBadConnect(socketArgs);
            }
        }
示例#27
0
        public TcpConnectionManager(string connectionName,
                                    TcpServiceType serviceType,
                                    ITcpDispatcher dispatcher,
                                    IPublisher publisher,
                                    ITcpConnection openedConnection,
                                    IPublisher networkSendQueue,
                                    IAuthenticationProvider authProvider,
                                    TimeSpan heartbeatInterval,
                                    TimeSpan heartbeatTimeout,
                                    Action <TcpConnectionManager, SocketError> onConnectionClosed,
                                    int connectionPendingSendBytesThreshold,
                                    int connectionQueueSizeThreshold)
        {
            Ensure.NotNull(dispatcher, "dispatcher");
            Ensure.NotNull(publisher, "publisher");
            Ensure.NotNull(openedConnection, "openedConnnection");
            Ensure.NotNull(networkSendQueue, "networkSendQueue");
            Ensure.NotNull(authProvider, "authProvider");

            ConnectionId   = openedConnection.ConnectionId;
            ConnectionName = connectionName;

            _serviceType  = serviceType;
            _tcpEnvelope  = new SendOverTcpEnvelope(this, networkSendQueue);
            _publisher    = publisher;
            _dispatcher   = dispatcher;
            _authProvider = authProvider;

            _framer = new LengthPrefixMessageFramer();
            _framer.RegisterMessageArrivedCallback(OnMessageArrived);

            _weakThisEnvelope  = new SendToWeakThisEnvelope(this);
            _heartbeatInterval = heartbeatInterval;
            _heartbeatTimeout  = heartbeatTimeout;
            _connectionPendingSendBytesThreshold = connectionPendingSendBytesThreshold;
            _connectionQueueSizeThreshold        = connectionQueueSizeThreshold;

            _connectionClosed = onConnectionClosed;

            RemoteEndPoint = openedConnection.RemoteEndPoint;
            _connection    = openedConnection;
            _connection.ConnectionClosed += OnConnectionClosed;
            if (_connection.IsClosed)
            {
                OnConnectionClosed(_connection, SocketError.Success);
                return;
            }

            ScheduleHeartbeat(0);
        }
示例#28
0
 private void OnMessageArrived(ITcpConnection connection, byte[] message)
 {
     try
     {
         _messageArrivedHandler(connection, message, reply =>
         {
             Task.Factory.StartNew(() => connection.QueueMessage(reply));
         });
     }
     catch (Exception ex)
     {
         _logger.Error(string.Format("Socket server handle message has exception, name: {0}, listeningEndPoint: {1}", _name, _listeningEndPoint), ex);
     }
 }
 private void OnRawDataReceived(ITcpConnection connection, IEnumerable <ArraySegment <byte> > data)
 {
     try
     {
         _framer.UnFrameData(data);
     }
     catch (PackageFramingException exc)
     {
         Log.InfoException(exc, "Invalid TCP frame received.");
         Close("Invalid TCP frame received.");
         return;
     }
     connection.ReceiveAsync(OnRawDataReceived);
 }
示例#30
0
 private void OnConnectionClosed(ITcpConnection connection, SocketError socketError)
 {
     foreach (var listener in _connectionEventListeners)
     {
         try
         {
             listener.OnConnectionClosed(connection, socketError);
         }
         catch (Exception ex)
         {
             _logger.Error(string.Format("Notify connection closed failed, listener type:{0}", listener.GetType().Name), ex);
         }
     }
 }
示例#31
0
 private void OnMessageArrived(ITcpConnection connection, byte[] message)
 {
     try
     {
         _messageArrivedHandler(connection, message, reply =>
         {
             Task.Factory.StartNew(() => connection.QueueMessage(reply));
         });
     }
     catch (Exception ex)
     {
         _logger.Error("Handle message error.", ex);
     }
 }
示例#32
0
 private void OnConnectionClosed(ITcpConnection connection, SocketError socketError)
 {
     foreach (var listener in _connectionEventListeners)
     {
         try
         {
             listener.OnConnectionClosed(connection, socketError);
         }
         catch (Exception ex)
         {
             _logger.Error(string.Format("Client socket notify connection closed has exception, name: {0}, listenerType: {1}", Name, listener.GetType().Name), ex);
         }
     }
 }
        private void OnConnectionClosed(ITcpConnection connection, SocketError socketError)
        {
            Log.Info("Connection [{0}] closed: {1}.", connection.EffectiveEndPoint, socketError);

            _isClosed = true;
            connection.ConnectionClosed -= OnConnectionClosed;

            var handler = ConnectionClosed;

            if (handler != null)
            {
                handler(this, socketError);
            }
        }
示例#34
0
 private void OnConnectionClosed(ITcpConnection connection, SocketError socketError)
 {
     foreach (var listener in _connectionEventListeners)
     {
         try
         {
             listener.OnConnectionClosed(connection, socketError);
         }
         catch (Exception ex)
         {
             _logger.Error(string.Format("Notify connection closed failed, listener type:{0}", listener.GetType().Name), ex);
         }
     }
 }
        private void OnRawDataReceived(ITcpConnection connection, IEnumerable <ArraySegment <byte> > data)
        {
            Interlocked.Increment(ref _messageNumber);

            try {
                _framer.UnFrameData(data);
            } catch (PackageFramingException exc) {
                SendBadRequestAndClose(Guid.Empty,
                                       string.Format("Invalid TCP frame received. Error: {0}.", exc.Message));
                return;
            }

            _connection.ReceiveAsync(OnRawDataReceived);
        }
示例#36
0
        public void when_connection_closed_quickly_socket_should_be_properly_disposed()
        {
            for (int i = 0; i < 1000; i++)
            {
                var            listeningSocket     = CreateListeningSocket();
                ITcpConnection clientTcpConnection = null;
                ITcpConnection serverTcpConnection = null;
                Socket         serverSocket        = null;
                try {
                    ManualResetEventSlim mre = new ManualResetEventSlim(false);

                    clientTcpConnection = TcpConnectionSsl.CreateConnectingConnection(
                        Guid.NewGuid(),
                        (IPEndPoint)listeningSocket.LocalEndPoint,
                        "localhost",
                        false,
                        new TcpClientConnector(),
                        TimeSpan.FromSeconds(5),
                        (conn) => {},
                        (conn, error) => {},
                        false);

                    clientTcpConnection.ConnectionClosed += (conn, error) => {
                        mre.Set();
                    };

                    serverSocket = listeningSocket.Accept();
                    clientTcpConnection.Close("Intentional close");
                    serverTcpConnection = TcpConnectionSsl.CreateServerFromSocket(Guid.NewGuid(),
                                                                                  (IPEndPoint)serverSocket.RemoteEndPoint, serverSocket, GetCertificate(), false);

                    mre.Wait(TimeSpan.FromSeconds(10));
                    SpinWait.SpinUntil(() => serverTcpConnection.IsClosed, TimeSpan.FromSeconds(10));

                    var disposed = false;
                    try {
                        int x = serverSocket.Available;
                    } catch (ObjectDisposedException) {
                        disposed = true;
                    }

                    Assert.True(disposed);
                } finally {
                    clientTcpConnection?.Close("Shut down");
                    serverTcpConnection?.Close("Shut down");
                    listeningSocket.Dispose();
                    serverSocket?.Dispose();
                }
            }
        }
        private string ResponseHandShake(ITcpConnection connection, int dataPacketId, string dataPacketToken, SendData sendData)
        {
            var handShake    = JsonConvert.DeserializeObject <HandShakeRequest>(sendData.MessageData);
            var requestState = RequestState.Success;

            // create token here
            int userIndex = Index;
            var salted    = (handShake.AccountName + userIndex).GetHashCode();
            var userToken = salted.ToString();
            //Console.WriteLine($"Hash: {salted} -> {token}");

            var newUserInfo = new UserInfoData
            {
                Id          = userIndex,
                Token       = userToken,
                AccountName = handShake.AccountName,
                Connection  = connection,
                UserState   = UserState.None,
                GameId      = -1,
                DeckType    = DeckType.None,
                DeckData    = string.Empty,
                PlayerState = PlayerState.None
            };

            var user = _registredUsers.Values.ToList().Find(p => p.AccountName == handShake.AccountName);

            if (user != null && user.Connection.Equals(connection))
            {
                Log.Warn($"Account {handShake.AccountName} already registred! EndPoint: {user.Connection.LocalEndPoint}, Key: {user.Connection.Key}, {user.Connection.Equals(connection)}");
                requestState = RequestState.Fail;
            }
            else if (user != null && !_registredUsers.TryUpdate(user.Token, newUserInfo, user))
            {
                Log.Warn($"Account {handShake.AccountName} couldn't be updated!");
                requestState = RequestState.Fail;
            }
            else if (!_registredUsers.TryAdd(userToken, newUserInfo))
            {
                Log.Warn($"Account {handShake.AccountName} couldn't be registred!");
                requestState = RequestState.Fail;
            }

            if (requestState == RequestState.Success)
            {
                Log.Info($"Registred account {handShake.AccountName}!");
            }

            return(DataPacketBuilder.ResponseServerHandShake(_id, _token, requestState, userIndex, userToken));
        }
        public static async Task <int> SendAsync(this ITcpConnection connection, string data, Encoding encoding = null)
        {
            int bytesSent = -1;

            try
            {
                bytesSent = await connection.Instance.SendAsync(data, encoding);
            }
            catch
            {
                bytesSent = -1;
            }

            return(bytesSent);
        }
示例#39
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NetServerEventArgs"/> class.
 /// </summary>
 /// <param name="tcpServer">The TCP server.</param>
 /// <param name="localEndPoint">The local end point.</param>
 /// <param name="connection">The connection.</param>
 public NetServerEventArgs(ITcpServer tcpServer, IPEndPoint localEndPoint = null, ITcpConnection connection = null)
 {
     if (tcpServer != null)
     {
         TcpServer = tcpServer;
     }
     if (localEndPoint != null)
     {
         LocalEndPoint = localEndPoint;
     }
     if (connection != null)
     {
         Connection = connection;
     }
 }
示例#40
0
 public void RemoveBroker(ITcpConnection connection)
 {
     using (_asyncLock.Lock())
     {
         var connectionId = connection.RemotingEndPoint.ToAddress();
         var broker       = FindBroker(connectionId);
         if (broker != null)
         {
             if (broker.Group.Brokers.TryRemove(broker.BrokerInfo.BrokerName, out Broker removed))
             {
                 _logger.InfoFormat("Removed broker, brokerInfo: {0}", _jsonSerializer.Serialize(removed.BrokerInfo));
             }
         }
     }
 }
        /// <summary>
        /// Connects asynchronous.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException">Cannot connect because current state is  + _state</exception>
        public async Task ConnectAsync(string uri, CancellationToken cancellationToken)
        {
            var oldState = Interlocked.CompareExchange(ref _state, WebSocketState.Connecting, WebSocketState.Closed);
            if (oldState != WebSocketState.Closed)
                throw new InvalidOperationException(ErrorMessages.InvalidState + _state);

            if (uri == null)
                throw new ArgumentNullException("uri");

            _uri = WebSocketHelper.CreateWebSocketUri(uri);
            
            var useSsl = _uri.Scheme == "wss";
            _tcp = await this.ConnectAsync(_uri.DnsSafeHost, _uri.Port, useSsl, cancellationToken);            
            Interlocked.Exchange(ref _state, WebSocketState.Connected);
        }
        public void ProcessData(ITcpConnection cNetConnection, int dataPacketId, string dataPacketToken, GameData gameData)
        {
            switch (gameData.GameMessageType)
            {
            case GameMessageType.GameResponse:
                ProcessGameResponse(dataPacketId, dataPacketToken, JsonConvert.DeserializeObject <GameResponse>(gameData.GameMessageData));
                break;

            case GameMessageType.GameRequest:
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
示例#43
0
        private void OnConnectionClosed(ITcpConnection connection, SocketError socketError)
        {
            if (Interlocked.CompareExchange(ref _isClosed, 1, 0) != 0)
            {
                return;
            }
            Log.Info("Connection '{0}#{1:d}' [{2}] closed: {3}.", ConnectionName, ConnectionId, connection.RemoteEndPoint, socketError);

            if (_connectionClosed != null)
            {
                _connectionClosed(this, socketError);
            }

            _framer.Cleanup();
        }
示例#44
0
 public void RegisterProducer(string producerId, ITcpConnection connection)
 {
     _producerDict.AddOrUpdate(producerId, key =>
     {
         _logger.InfoFormat("Producer registered, producerId: {0}", key);
         return(new ProducerHeartbeatInfo(connection)
         {
             LastHeartbeatTime = DateTime.Now
         });
     }, (key, existing) =>
     {
         existing.LastHeartbeatTime = DateTime.Now;
         return(existing);
     });
 }
示例#45
0
 private void OnConnectionClosed(ITcpConnection connection, SocketError socketError)
 {
     _connectionDict.Remove(connection.Id);
     foreach (var listener in _connectionEventListeners)
     {
         try
         {
             listener.OnConnectionClosed(connection, socketError);
         }
         catch (Exception ex)
         {
             _logger.Error(string.Format("Notify socket server client connection closed has exception, name: {0}, listenerType: {1}", _name, listener.GetType().Name), ex);
         }
     }
 }
        private string ResponseQueue(ITcpConnection connection, int dataPacketId, string dataPacketToken, SendData sendData)
        {
            var requestState = RequestState.Success;

            if (_registredUsers.TryGetValue(dataPacketToken, out UserInfoData userInfoData) && userInfoData.UserState == UserState.None)
            {
                ChangeUserState(userInfoData, UserState.Queued);
            }
            else
            {
                requestState = RequestState.Fail;
            }

            return(DataPacketBuilder.ResponseServerQueue(_id, _token, requestState, 0));
        }
示例#47
0
 public ChatWorker(ILoggerFactory loggerFactory, ICancellation cancellation, AppState appState, AppRepository appRepository, ITcpConnection tcpConnection, IUdpConnection udpConnection, IChatClient chatClient, IXDSSecService ixdsCryptoService, IChatEncryptionService chatEncryptionService, E2ERatchet e2eRatchet, ContactListManager contactListManager)
 {
     this.logger                = loggerFactory.CreateLogger <ChatWorker>();
     this.appState              = appState;
     this.repo                  = appRepository;
     this.tcp                   = tcpConnection;
     this.udp                   = udpConnection;
     this.chatClient            = chatClient;
     this.ixdsCryptoService     = ixdsCryptoService;
     this.chatEncryptionService = chatEncryptionService;
     this.e2eRatchet            = e2eRatchet;
     this.contactListManager    = contactListManager;
     this.cancellation          = cancellation;
     cancellation.RegisterWorker(this);
 }
示例#48
0
            public void OnConnectionClosed(ITcpConnection connection, SocketError socketError)
            {
                var operateID = Guid.NewGuid().ToString();
                var lockkey   = connection.RemotingEndPoint.ToString();

                if (_lock.LockTake(lockkey, operateID, TimeSpan.FromSeconds(10)))
                {
                    _clientPool.ConnectedClientList.Remove(_client);
                    _clientPool.CurrentCount -= 1;
                    _lock.LockRelease(lockkey, operateID);
                }
                else
                {
                    OnConnectionClosed(connection, socketError);
                }
            }
示例#49
0
 public void RegisterProducer(ITcpConnection connection, string producerId)
 {
     var connectionId = connection.RemotingEndPoint.ToAddress();
     _producerInfoDict.AddOrUpdate(connectionId, key =>
     {
         var producerInfo = new ProducerInfo
         {
             ProducerId = producerId,
             HeartbeatInfo = new ClientHeartbeatInfo(connection) { LastHeartbeatTime = DateTime.Now }
         };
         _logger.InfoFormat("Producer registered, producerId: {0}, connectionId: {1}", producerId, key);
         return producerInfo;
     }, (key, existingProducerInfo) =>
     {
         existingProducerInfo.HeartbeatInfo.LastHeartbeatTime = DateTime.Now;
         return existingProducerInfo;
     });
 }
示例#50
0
        public void RegisterConsumer(ITcpConnection connection, string consumerId, IList<string> subscriptionTopics, IList<MessageQueueEx> consumingMessageQueues)
        {
            var connectionId = connection.RemotingEndPoint.ToAddress();

            _consumerInfoDict.AddOrUpdate(connectionId, key =>
            {
                var newConsumerInfo = new ConsumerInfo
                {
                    ConsumerId = consumerId,
                    HeartbeatInfo = new ClientHeartbeatInfo(connection) { LastHeartbeatTime = DateTime.Now },
                    SubscriptionTopics = subscriptionTopics,
                    ConsumingQueues = consumingMessageQueues
                };
                _logger.InfoFormat("Consumer registered to group, groupName: {0}, consumerId: {1}, connectionId: {2}, subscriptionTopics: {3}, consumingQueues: {4}", _groupName, consumerId, key, string.Join("|", subscriptionTopics), string.Join("|", consumingMessageQueues));
                return newConsumerInfo;
            },
            (key, existingConsumerInfo) =>
            {
                existingConsumerInfo.HeartbeatInfo.LastHeartbeatTime = DateTime.Now;

                var oldSubscriptionList = existingConsumerInfo.SubscriptionTopics.ToList();
                var newSubscriptionList = subscriptionTopics.ToList();
                if (IsStringCollectionChanged(oldSubscriptionList, newSubscriptionList))
                {
                    existingConsumerInfo.SubscriptionTopics = newSubscriptionList;
                    _logger.InfoFormat("Consumer subscriptionTopics changed. groupName: {0}, consumerId: {1}, connectionId: {2}, old: {3}, new: {4}", _groupName, consumerId, key, string.Join("|", oldSubscriptionList), string.Join("|", newSubscriptionList));
                }

                var oldConsumingQueues = existingConsumerInfo.ConsumingQueues;
                var newConsumingQueues = consumingMessageQueues;
                if (IsMessageQueueChanged(oldConsumingQueues, newConsumingQueues))
                {
                    existingConsumerInfo.ConsumingQueues = newConsumingQueues;
                    _logger.InfoFormat("Consumer consumingQueues changed. groupName: {0}, consumerId: {1}, connectionId: {2}, old: {3}, new: {4}", _groupName, consumerId, key, string.Join("|", oldConsumingQueues), string.Join("|", newConsumingQueues));
                }

                return existingConsumerInfo;
            });
        }
示例#51
0
        private void OnDataReceived(ITcpConnection conn, IEnumerable<ArraySegment<byte>> data)
        {
            IMessageFramer framer;
            Tuple<ITcpConnection, IMessageFramer> pair;
            if (!_clientFramers.TryGetValue(conn.ConnectionId, out pair))
            {
                framer = new CrappyTemporaryFramer();
                framer.RegisterMessageArrivedCallback(CompleteMessageArrived);
                _clientFramers.TryAdd(conn.ConnectionId, new Tuple<ITcpConnection, IMessageFramer>(conn, framer));

                //Note: we stick the connection ID in the first part of the message just so we
                // can find it later. This isn't especially nice and is fixed in real code
                var connectionId = conn.ConnectionId.ToByteArray();
                framer.UnFrameData(new ArraySegment<byte>(connectionId, 0, connectionId.Length));
            }
            else
            {
                framer = pair.Item2;
            }

            framer.UnFrameData(data);
            conn.ReceiveAsync(OnDataReceived);
        }
 public PendingConnection(ITcpConnection connection, DateTime whenToKill)
 {
     Connection = connection;
     WhenToKill = whenToKill;
 }
示例#53
0
 public BaseTextProto(ITcpConnection connection, ICommandFactory commandFactory, int id)
     : base(connection, commandFactory, id)
 {
 }
示例#54
0
文件: Consumer.cs 项目: uliian/equeue
 public void OnConnectionClosed(ITcpConnection connection, SocketError socketError)
 {
     _consumer.StopBackgroundJobs();
 }
示例#55
0
文件: Consumer.cs 项目: uliian/equeue
 public void OnConnectionEstablished(ITcpConnection connection)
 {
     _consumer.StartBackgroundJobs();
 }
示例#56
0
文件: Consumer.cs 项目: uliian/equeue
 public void OnConnectionAccepted(ITcpConnection connection)
 {
 }
 private int ReceiveData(ITcpConnection tcpConnection, IEnumerable<ArraySegment<byte>> data)
 {
     int value = data.Sum (v => v.Count);
     _totalReceived [tcpConnection] += (long)value;
     Interlocked.Add (ref _received, value);
     return value;
 }
        private void SendRandomData(ITcpConnection tcpConnection, bool small)
        {
            var rnd = new Random ();
            WaitCallback callBack = state =>
            {

                var outData = new List<ArraySegment<byte>> ();
                int index = 0;

                int size = 1 + ((!small && rnd.Next (2) == 0) ? _data.Length/2 + rnd.Next (_data.Length/2) : rnd.Next (32));
                int totalSize = 0;
                outData.Add (new ArraySegment<byte> (_data, index, size));
                totalSize += size;
                Interlocked.Add (ref _sent, size);
                _totalSent [tcpConnection] += totalSize;
                tcpConnection.EnqueueSend (outData);
            };

            if (rnd.Next (5) != 0) {
                small = true;
                var loopCount = rnd.Next(10000);
                var nextRnd = 	 rnd.Next (4);
                for (var k = 0; k < 10; k++)
                    ThreadPool.QueueUserWorkItem (v =>
                    {
                        long h = 1;
                        // random cpu busy delay
                        for (long i = 0; i < loopCount; i++)
                            h = h + i;
                    // randon cpu free delay
                        callBack (null);
                        if (!small && nextRnd == 0) {
                            //Thread.Sleep (rnd.Next (5));
                            ThreadPool.QueueUserWorkItem (callBack);
                        }
                    }
                    );
            }
            else
            {
                callBack (null);
            //				callBack (null);
            //				callBack (null);
            }
        }
 private void ReceiveAndSend(ITcpConnection tcpConnection, IEnumerable<ArraySegment<byte>> arraySegments)
 {
     var received = ReceiveData(tcpConnection, arraySegments);
     SendRandomData(tcpConnection, small: _totalSent[tcpConnection] - _totalReceived[tcpConnection] > 32768 || received > 64);
 }
 private void ClientReceiveCallback(ITcpConnection tcpConnection, IEnumerable<ArraySegment<byte>> arraySegments)
 {
     tcpConnection.ReceiveAsync(ClientReceiveCallback);
     ReceiveAndSend(tcpConnection, arraySegments);
 }