Exemplo n.º 1
0
        protected async Task DisconnectionCheckLoopAsync()
        {
            while (Running)
            {
                TcpClient[] clients;
                lock (ClientsLocker)
                    clients = this.Clients.ToArray();

                if (clients != null)
                {
                    for (int i = 0; i < clients.Length; i++)
                    {
                        if (clients[i].Client != null && !clients[i].Client.Connected)
                        {
                            OnClientDisconnect?.Invoke(clients[i], DisconnectReason.Timeout.ToString());

                            DisconnectClient(clients[i], DisconnectReason.Timeout.ToString());
                        }
                    }
                }

                int waitTime = (int)((1.0D / PingRate) * 1000.0D);

                await Task.Delay(waitTime);
            }
        }
Exemplo n.º 2
0
 /// <summary>
 ///     Disconnects the client
 /// </summary>
 internal void Disconnect()
 {
     _tcpConnection.Disconnect();
     _udpConnection.Disconnect();
     _clientRegistry.UnregisterClient(this);
     OnClientDisconnect.Invoke(this);
 }
Exemplo n.º 3
0
        /// <summary>
        /// Ожидание приема команд от клиента
        /// </summary>
        /// <param name="clientId"></param>
        private void AwaitRecieveData(Guid clientId)
        {
            HandlerSocket rcvSocket;

            lock (HandlerSockets)
            {
                if (!HandlerSockets.ContainsKey(clientId))
                {
                    return;
                }
                rcvSocket = HandlerSockets[clientId];
            }

            try
            {
                var p = new Packet(rcvSocket);
                rcvSocket.Socket.BeginReceive(p.Buffer, 0, p.Buffer.Length, SocketFlags.None, ReceiveData, p);
            }
            catch (SocketException socketException)
            {
                OnClientDisconnect?.Invoke(clientId);
                Debug.WriteLine(socketException.Message);
            }
            catch (Exception e)
            {
                var messageError = e.InnerException?.Message ?? e.Message;
                Debug.WriteLine(messageError);
            }
        }
Exemplo n.º 4
0
        internal void DisconnectClient(WebSocketsClient wsclient)
        {
            if (wsclient.Socket.Connected)
            {
                OnClientDisconnect?.Invoke(this, new WebSocketsClientEventArgs(wsclient));
                clients.Remove(wsclient);

                try
                {
                    wsclient.Stream.Close();
                }
                catch (Exception e)
                {
                    OnError?.Invoke(this, new WebSocketsErrorEventArgs(e));
                }

                try
                {
                    wsclient.Stream.Dispose();
                }
                catch (Exception e)
                {
                    OnError?.Invoke(this, new WebSocketsErrorEventArgs(e));
                }

                try
                {
                    wsclient.Socket.Close();
                }
                catch (Exception e)
                {
                    OnError?.Invoke(this, new WebSocketsErrorEventArgs(e));
                }
            }
        }
Exemplo n.º 5
0
 void HandleDisconnect(CClientSocket ClientSocket)
 {
     if (OnClientDisconnect != null)
     {
         OnClientDisconnect.Invoke(ClientSocket);
     }
 }
Exemplo n.º 6
0
        private void ClientDisconnect(DisconnectionContext ctx, ConnectionInfo inf)
        {
            lock (LockObject)
            {
                for (int i = 0; i < ClientCount; i++)
                {
                    if (!Clients[i].connectionInfo.Equals(inf))
                    {
                        continue;
                    }
                    if (Clients[i].DisconnectionMode.type == DisconnectionContext.DisconnectionType.REMOVE)
                    {
                        Clients.RemoveAt(i);
                        i--;
                    }
                    else if ((int)Clients[i].DisconnectionMode.type == 2 && GlobalDefaults.ForcibleDisconnectMode == 0)
                    {
                        Clients.RemoveAt(i);
                        i--;
                    }
                }

                OnClientDisconnect?.Invoke(ctx, inf);
            }
            if (RestartAutomatically && !Running && ClientCount < MaxClients)
            {
                StartServer();
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Обработчик события при попытке принять входящее соединение
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="socketArgs"></param>
        private void AcceptSocketOnCompleted(object sender, SocketAsyncEventArgs socketArgs)
        {
            if (socketArgs.SocketError != SocketError.Success)
            {
                return;
            }

            lock (HandlerSockets)
            {
                _currentClientId = Guid.NewGuid();
                var hSocket = new HandlerSocket(socketArgs.AcceptSocket, _currentClientId);
                HandlerSockets.Add(_currentClientId, hSocket);
                OnClientConnect?.Invoke(_currentClientId);
            }

            try
            {
                AwaitRecieveData(_currentClientId);
                var argsAcceptSocket = new SocketAsyncEventArgs();
                argsAcceptSocket.Completed += AcceptSocketOnCompleted;
                _listenerSocket.AcceptAsync(argsAcceptSocket);
            }
            catch (SocketException socketException)
            {
                OnClientDisconnect?.Invoke(_currentClientId);
                Debug.WriteLine(socketException.Message);
            }
        }
Exemplo n.º 8
0
 protected virtual void DisconnectClient(TcpClient client, string reason)
 {
     OnClientDisconnect?.Invoke(client, reason);
     new NetKick(reason).Send(client.Client);
     client.Close();
     client.Dispose();
     lock (ClientsLocker)
         Clients.Remove(client);
 }
Exemplo n.º 9
0
 public void InitThreads()
 {
     _thRecv = new Thread(() =>
     {
         while (_isAlive)
         {
             ProcessRecvQueue();
             SignalPacketRecv.WaitOne(RecvWaitMs);
         }
     });
     _thKeepAlive = new Thread(() =>
     {
         while (_isAlive)
         {
             DateTime dtNow = DateTime.Now;
             List <string> offlineEndpoints = new List <string>();
             List <RUDPConnectionData> cons = new List <RUDPConnectionData>();
             lock (_connectionsMutex)
                 cons.AddRange(Connections.Select(x => x.Value));
             Parallel.ForEach(cons, (cn) =>
             {
                 if ((dtNow - cn.LastKeepAliveDate).Seconds >= KeepAliveInterval)
                 {
                     cn.LastKeepAliveDate = dtNow;
                     SendKeepAlive(cn.EndPoint);
                     lock (cn.Pending)
                         foreach (RUDPPacket p in cn.Pending)
                         {
                             RetransmitPacket(p);
                         }
                 }
                 if ((dtNow - cn.LastPacketDate).Seconds >= ConnectionTimeout)
                 {
                     Debug("TIMEOUT");
                     if (!IsServer)
                     {
                         Disconnect();
                     }
                     else
                     {
                         offlineEndpoints.Add(cn.EndPoint.ToString());
                     }
                 }
             });
             lock (_connectionsMutex)
                 foreach (string ep in offlineEndpoints)
                 {
                     OnClientDisconnect?.Invoke(Connections[ep].EndPoint);
                     Debug("-Connection {0}", ep);
                     Connections.Remove(ep);
                 }
             Thread.Sleep(10);
         }
     });
     _thRecv.Start();
     _thKeepAlive.Start();
 }
Exemplo n.º 10
0
        /// <summary>
        /// Send a message to all connected clients.
        /// </summary>
        /// <param name="message">A byte array representing the message to send.</param>
        /// <param name="testConnections"></param>
        public void SendMessage(byte[] message, bool testConnections = false)
        {
            if (testConnections)
            {
                var clientsToRemove = new List <int>();
                foreach (var clientId in WorkerSockets.Keys)
                {
                    if (WorkerSockets[clientId].UserSocket.Connected)
                    {
                        try
                        {
                            WorkerSockets[clientId].UserSocket.Send(message);
                        }
                        catch
                        {
                            clientsToRemove.Add(clientId);
                        }

                        Thread.Sleep(10); // this is for a client Ping so stagger the send messages
                    }
                    else
                    {
                        clientsToRemove.Add(clientId);
                    }
                }


                if (clientsToRemove.Count > 0)
                {
                    foreach (var cId in clientsToRemove)
                    {
                        OnClientDisconnect?.Invoke(cId);
                    }
                }
                clientsToRemove.Clear();
            }
            else
            {
                foreach (var s in WorkerSockets.Values)
                {
                    try
                    {
                        if (s.UserSocket.Connected)
                        {
                            s.UserSocket.Send(message);
                        }
                    }
                    catch (SocketException se)
                    {
                        Console.WriteLine(se.Message);
                    }
                }
            }
        }
Exemplo n.º 11
0
        public void DisconnectClient(Connection client)
        {
            if (client.IsConnected)
            {
                client.Disconnect();
            }

            UnsubscribeOnClient(client);

            connections.Remove(connections.FirstOrDefault(x => x == client));;
            OnClientDisconnect.Invoke(client);
        }
Exemplo n.º 12
0
 private void ExtendedClientLeftView(object sender, IEnumerable <ClientLeftView> eventArgs)
 {
     clientbufferOutdated = true;
     if (OnClientDisconnect == null)
     {
         return;
     }
     foreach (var evData in eventArgs)
     {
         clientbufferOutdated = true;
         OnClientDisconnect?.Invoke(sender, evData);
     }
 }
Exemplo n.º 13
0
 private void ClientDisconnect()
 {
     clientSock.GetStream().Close();
     clientSock.Close();
     clientSock.Dispose();
     stream.Close();
     stream.Dispose();
     receiveBuffer = null;
     stream        = null;
     clientSock    = null;
     onClientDisconnect?.Invoke(id);
     udpClient = null;
     updateClients?.Invoke(room);
 }
Exemplo n.º 14
0
 private void CallClientDisconnect(int clientId)
 {
     try
     {
         OnClientDisconnect?.Invoke(this, new ConnectionArgs(clientId));
     }
     catch (Exception ex)
     {
         if (_showFail)
         {
             Debug.Fail(ex.Message, ex.StackTrace);
         }
     }
 }
Exemplo n.º 15
0
        private void SetOnClientDisconnect(Operation Client, string Reason)
        {
            OnClientDisconnect?.Invoke(Client, Reason);
            ShutdownResult ShutdownResult = Shutdown();

            if (ShutdownResult.IsOperationSuccess)
            {
                Console.WriteLine(ShutdownResult.Message);
            }
            else
            {
                Console.WriteLine(ShutdownResult.Message);
            }
        }
Exemplo n.º 16
0
        public void RemoveClient(Client client)
        {
            client.OnPacketReceive -= Client_OnPacketReceive;
            client.OnDisconnect    -= Client_OnDisconnect;

            // if the client was added we will remove it
            if (client.NetworkId != null)
            {
                ConnectedClients.TryRemove(client.NetworkId, out client);
                OnClientDisconnect?.Invoke(this, new ClientStateChangeArgs(client.NetworkId, client));
            }

            client.Dispose();
        }
Exemplo n.º 17
0
        /// <summary>
        /// Manuseia Comunicação do Cliente
        /// </summary>
        private void HandlePlayer(object obj)
        {
            //Recebe cliente a partir do parâmetro
            TcpClient tcpClient = (TcpClient)obj;

            var Player = OnConnectPlayer(tcpClient);

            //Chama evento OnClientConnected
            PlayerConnect(Player);

            while (Player.Connected)
            {
                try
                {
                    byte[] message = ReceivePacket(tcpClient.GetStream());

                    if (message.Length >= 5)
                    {
                        if (Player.Connected)
                        {
                            var packet = new Packet(message, Player.GetKey);
                            if (ShowLog)
                            {
                                packet.Log();
                            }
                            //Dispara evento OnPacketReceived
                            PlayerRequestPacket(Player, packet);
                        }
                    }
                    else
                    {
                        if (Player.Connected)
                        {
                            OnClientDisconnect?.Invoke(Player);
                            DisconnectPlayer(Player);
                        }
                    }
                }
                catch (Exception ex)
                {
                    OnClientDisconnect?.Invoke(Player);
                    ServerExpection(Player, ex);
                }
            }
            if (Player.Connected)
            {
                DisconnectPlayer(Player);
            }
        }
Exemplo n.º 18
0
        private void HandleConnection()
        {
            try
            {
                while (true)
                {
                    //Check status of current connections
                    lock (_lock)
                    {
                        foreach ((string key, ClientSocket socket) in _clientSockets.ToList().Where(x => !x.Value.IsConnected()))
                        {
                            socket.Disconnect();
                            _clientSockets.Remove(key);
                            OnClientDisconnect?.Invoke(socket.ClientId);
                        }
                    }

                    //Check for new connections
                    if (_listener.Pending())
                    {
                        //Accept new client
                        ClientSocket newSocket = new ClientSocket(Guid.NewGuid().ToString(), _listener.AcceptTcpClient());

                        //Add new client to list
                        lock (_lock)
                        {
                            _clientSockets.Add(newSocket.ClientId, newSocket);
                        }

                        OnClientConnect?.Invoke(newSocket);

                        //Fire client connection and authentication events
                        newSocket.Emit("connect");
                        newSocket.Emit("authentication");
                    }
                    else
                    {
                        //Waits half a second if no pending connections to preserve performance of machine
                        Thread.Sleep(500);
                    }
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
                Stop();
            }
        }
    public FizzySteamyMirror()
    {
        // dispatch the events from the server
        server.OnConnected += (id) => OnServerConnect?.Invoke(id);
        server.OnDisconnected += (id) => OnServerDisconnect?.Invoke(id);
        server.OnReceivedData += (id, data) => OnServerData?.Invoke(id, data);
        server.OnReceivedError += (id, exception) => OnServerError?.Invoke(id, exception);

        // dispatch events from the client
        client.OnConnected += () => OnClientConnect?.Invoke();
        client.OnDisconnected += () => OnClientDisconnect?.Invoke();
        client.OnReceivedData += (data) => OnClientData?.Invoke(data);
        client.OnReceivedError += (exception) => OnClientError?.Invoke(exception);

        Debug.Log("FizzySteamyMirror initialized!");
    }
        /// <summary>
        /// Waits until an event is recieved by some client and it is returned with information about this client.
        /// </summary>
        /// <returns></returns>
        public async Task <InfoControllerEvent> RecieveEventAsync()
        {
            InfoControllerEvent result = default;

            while (true)
            {
                // Waits for first user.
                while (_events.Count == 0)
                {
                    await Task.Delay(25);
                }

                int index = -1;
                try
                {
                    index = Task.WaitAny(_events.ToArray(), _src.Token);
                }
                catch (OperationCanceledException)
                {
                    _src = new CancellationTokenSource();
                    continue;
                }

                result = await _events[index];

                if (GetClient(result.Sender).IsConnected)
                {
                    _events[index] = GetClient(result.Sender).ReceiveAsync();
                    break;
                }
                else
                {
                    lock (_playersLock)
                        _events.RemoveAt(index);

                    OnClientDisconnect?.Invoke(GetClient(result.Sender));

                    if (RemoveClientsAfterDisconnect)
                    {
                        await RemoveClient(result.Sender);
                    }
                }
            }

            return(result);
        }
Exemplo n.º 21
0
        protected override void DisconnectedByRemote(Socket socket)
        {
            try
            {
                IPEndPoint clientEndPoint = (IPEndPoint)socket.RemoteEndPoint;

                NetUtil.LogInfo(logTag, $"Client disconnected ({clientEndPoint.Address}:{clientEndPoint.Port})");
            }
            catch (Exception)
            {
                NetUtil.LogWarning(logTag, "TcpServerSocket::DisconnectedByRemote->Client disconnected.");
            }

            socket.Close();
            clients.Remove(socket);
            OnClientDisconnect?.Invoke(this, new TcpSocketEventArgs(socket));
        }
Exemplo n.º 22
0
        private void EnqueueIncomingPacket(NetWrapper netWrapper, uint binaryAddress, PacketId packetId, byte[] data)
        {
            if (!this.clients[netWrapper].ContainsKey(binaryAddress))
            {
                this.clients[netWrapper][binaryAddress] = new Client(binaryAddress, netWrapper);
                OnClientConnect?.Invoke(this.clients[netWrapper][binaryAddress]);
            }

            this.packetReducer.EnqueuePacket(this.clients[netWrapper][binaryAddress], packetId, data);

            if (packetId == PacketId.PACKET_ID_PLAYER_QUIT || packetId == PacketId.PACKET_ID_PLAYER_TIMEOUT)
            {
                this.clients[netWrapper][binaryAddress].IsConnected = false;
                OnClientDisconnect?.Invoke(this.clients[netWrapper][binaryAddress]);
                this.clients[netWrapper].Remove(binaryAddress);
            }
        }
Exemplo n.º 23
0
        private void AcceptCallback(IAsyncResult ar)
        {
            CancellationToken cancellationToken = (CancellationToken)ar.AsyncState;

            _waiterConnection.Release();
            Socket handler = _listenerSocket.EndAccept(ar);

            _logger.LogDebug($"Client connected - Handle: " + handler.Handle);
            var connection = _container.Resolve <TCPConnection>(new TypedParameter(typeof(Socket), handler));

            _connections.TryAdd(handler.Handle, connection);

            connection.OnReceivePacket += (s, e) => OnClientData?.Invoke(this, new Message((IConnection)s, e));
            connection.OnDisconnect    += (s, e) => OnClientDisconnect?.Invoke(this, (IConnection)s);

            OnClientConnect?.Invoke(this, connection);
            connection.StartListenData(cancellationToken, _options.Source, true);
        }
Exemplo n.º 24
0
        /// <summary>
        /// An internal callback triggered when a client connects to the server.
        /// </summary>
        /// <param name="async"></param>
        private void OnReceiveConnection(IAsyncResult async)
        {
            try
            {
                lock (WorkerSockets)
                {
                    Interlocked.Increment(ref _currentClientNumber); // Thread Safe
                    var us = new UserSock(_currentClientNumber, _mainSocket.EndAccept(async));
                    WorkerSockets.Add(_currentClientNumber, us);
                }

                OnClientConnect?.Invoke(_currentClientNumber);

                WaitForData(_currentClientNumber);
                _mainSocket.BeginAccept(OnReceiveConnection, null);
            }
            catch (ObjectDisposedException)
            {
                Console.WriteLine(@"OnClientConnection: Socket has been closed");
            }
            catch (SocketException se)
            {
                //Console.WriteLine("SERVER EXCEPTION in OnReceiveConnection: " + se.Message);
                Debug.WriteLine("SERVER EXCEPTION in OnReceiveConnection: " +
                                se.Message);                    //pe 4-22-2015

                if (WorkerSockets.ContainsKey(_currentClientNumber))
                {
                    Console.WriteLine(@"RemoteEndPoint: " +
                                      WorkerSockets[_currentClientNumber].UserSocket.RemoteEndPoint);
                    Console.WriteLine(@"LocalEndPoint: " +
                                      WorkerSockets[_currentClientNumber].UserSocket.LocalEndPoint);

                    Console.WriteLine(@"Closing socket from OnReceiveConnection");
                }

                //Socket gets closed and removed from OnClientDisconnect
                OnClientDisconnect?.Invoke(_currentClientNumber);
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Handle an incoming message from a remote client.
        /// </summary>
        /// <param name="msg">Incoming message.</param>
        private void HandleIncomingMessage(NetIncomingMessage msg)
        {
            switch (msg.MessageType)
            {
            case NetIncomingMessageType.ConnectionApproval:
                HandleIncomingConnection(msg);
                break;

            case NetIncomingMessageType.StatusChanged:
                switch (msg.SenderConnection.Status)
                {
                case NetConnectionStatus.Disconnected:
                    if (OnClientDisconnect != null)
                    {
                        OnClientDisconnect.Invoke(
                            msg.SenderConnection, null);
                    }
                    break;

                case NetConnectionStatus.Connected:
                    if (OnClientConnect != null)
                    {
                        OnClientConnect.Invoke(
                            msg.SenderConnection, null
                            );
                    }
                    break;
                }
                break;

            case NetIncomingMessageType.Data:
                if (OnClientMessageReceived != null)
                {
                    OnClientMessageReceived.Invoke(
                        msg.SenderConnection, msg
                        );
                }
                break;
            }
        }
Exemplo n.º 26
0
        void IServerTransportLayer.Update()
        {
            while (_server.GetNextMessage(out var msg))
            {
                var id = new PerChannelID(_channelId, msg.connectionId);

                switch (msg.eventType)
                {
                case Telepathy.EventType.Connected:
                    _serverConnectionCallback.Invoke(_server.GetClientAddress(msg.connectionId), id);
                    break;

                case Telepathy.EventType.Data:
                    _serverMessageCallback.Invoke(msg.data, id);
                    break;

                case Telepathy.EventType.Disconnected:
                    _serverDisconnectCallback.Invoke(id);
                    break;
                }
            }
        }
Exemplo n.º 27
0
        public void Publish(GameEvent gameEvent)
        {
            _logger.LogDebug("Handling publishing event of type {EventType}", gameEvent.Type);

            try
            {
                if (gameEvent.Type == GameEvent.EventType.Connect)
                {
                    OnClientConnect?.Invoke(this, gameEvent);
                }

                if (gameEvent.Type == GameEvent.EventType.Disconnect)
                {
                    OnClientDisconnect?.Invoke(this, gameEvent);
                }
            }

            catch (Exception ex)
            {
                _logger.LogError(ex, "Could not publish event of type {EventType}", gameEvent.Type);
            }
        }
Exemplo n.º 28
0
        bool IServerTransportLayer.Init(int channelId, OnClientConnect connectCallback, OnReceiveMessage messageCallback, OnClientDisconnect disconnectCallback)
        {
            _connection = new MiniUDP.NetCore(ConnectionToken, true);
            _channelId  = channelId;

            _clients = new Dictionary <int, MiniUDP.NetPeer>();
            _nextId  = 0;

            _connection.PeerConnected += (peer, token) =>
            {
                _clients.Add(_nextId, peer);

                var id = new PerChannelID(channelId, _nextId++);

                connectCallback.Invoke(peer.EndPoint.Address, id);

                peer.PayloadReceived += (netPeer, data, length) =>
                {
                    if (data.Length != length)
                    {
                        Array.Resize(ref data, length);
                    }

                    messageCallback.Invoke(data, id);
                };
            };
            _connection.PeerClosed += (peer, reason, kickReason, error) =>
            {
                var id = _clients.FirstOrDefault(i => i.Value == peer).Key;
                disconnectCallback.Invoke(new PerChannelID(_channelId, id));

                _clients.Remove(id);
            };

            return(true);
        }
Exemplo n.º 29
0
 private void SetOnClientDisconnect(Operation Client, string Reason)
 {
     OnClientDisconnect?.Invoke(Client, Reason);
 }
        public void Disconnect()
        {
            OnClientDisconnect?.Invoke(this);

            isDisconnectRequested = true;
        }