Exemplo n.º 1
0
        private void _OnDataReceive(IAsyncResult ar)
        {
            ClientObject Client = ar.AsyncState as ClientObject;

            if (Client == null)
            {
                return;
            }

            try
            {
                int ReceivedBytesCount = Client.TcpClient.Client.EndReceive(ar);
                if (ReceivedBytesCount <= 0)
                {
                    lock (ConnectedClients) { ConnectedClients.Remove(Client.TcpClient); _Parent.NotifyClientDisconnected(Client.TcpClient); return; }
                }

                byte[] ReceivedBytes = new byte[ReceivedBytesCount];
                Array.Copy(Client.Buffer, ReceivedBytes, ReceivedBytes.Length);

                Client.TcpClient.GetStream().BeginRead(Client.Buffer, 0, Client.Buffer.Length, _OnDataReceive, Client);
                _Parent.NotifyDataReceived(ReceivedBytes, Client.TcpClient);
            }
            catch { lock (ConnectedClients) { ConnectedClients.Remove(Client.TcpClient); _Parent.NotifyClientDisconnected(Client.TcpClient); } }
        }
Exemplo n.º 2
0
        public void UpdateGuiWithNewMessage(string message)
        {
            //switch thread to GUI thread to write to GUI       // Prof: sorgt dafür, dass der Thread in der GUI ausgeführt wird
            //damit es gleichzeitig abläuft
            //(Dispatcher extra erstellen => Render (Hintergrund) und GUI Threads => aktualisieren GUI)

            App.Current.Dispatcher.Invoke(() =>
            {
                string name = message.Split(':')[0];
                if (!ConnectedClients.Contains(name))
                {//not in list => add it
                    ConnectedClients.Add(name);
                }
                if (message.Contains("@quit"))
                {
                    server.DisconnectOneClient(name);
                    // Extra:
                    ConnectedClients.Remove(name);      // Client auch aus connectedClients Liste löschen
                }
                //neue Nachricht zu Nachrichten-Collection hinzufügen
                Messages.Add(message);

                // GUI informieren, dass Nachrichtenanzahl gestiegen ist
                RaisePropertyChanged("MessagesCnt");
            });
        }
Exemplo n.º 3
0
        public override Task OnDisconnected(bool stopCalled)
        {
            var disconnectedUser = ConnectedClients.FirstOrDefault(x => x.Id.Equals(Context.ConnectionId));

            ConnectedClients.Remove(disconnectedUser);

            using (var _contextDB = new db_chatjobsityEntities())
            {
                var _objDb_disco = new Disconnected()
                {
                    UserID    = disconnectedUser.UserName,
                    Fe_Salida = System.DateTime.UtcNow.AddHours(-5)
                };
                _contextDB.Disconnected.Add(_objDb_disco);
                _contextDB.SaveChanges();

                var _discoUser = (from x in _contextDB.Disconnected
                                  orderby x.Fe_Salida descending
                                  select x).AsEnumerable().Take(50);
                var _discoUserX = (from x in _discoUser
                                   select new { UserName = x.Fe_Salida.ToString("yyyy-MM-dd HH:mm:ss") + " - " + x.UserID.ToString() }).ToList();

                Clients.All.updateUsers(ConnectedClients.Count(), ConnectedClients.Select(x => x.UserName), _discoUserX.Select(x => x.UserName));
            }
            return(base.OnDisconnected(stopCalled));
        }
Exemplo n.º 4
0
        //Handles messages
        protected override void HandleMessage(IAsyncResult result)
        {
            var state = (SocketState)result.AsyncState;

            try
            {
                //Check if client is still connected.
                //If client is disconnected, send disconnected message
                //and remove from clients list
                if (!IsConnected(state.Id))
                {
                    ClientDisconnectedInvoke(state.Id);
                    lock (ConnectedClients)
                    {
                        ConnectedClients.Remove(state.Id);
                    }
                }
                //Else start receiving and handle the message.
                else
                {
                    var receive = state.SslStream.EndRead(result);

                    _mreRead.Set();
                    //var receive = state.Listener.EndReceive(result);

                    if (state.Flag == 0)
                    {
                        state.CurrentState = new InitialHandlerState(state, null, this);
                    }

                    if (receive > 0)
                    {
                        state.CurrentState.Receive(receive);
                    }

                    /*When the full message has been received. */
                    if (state.Read == state.MessageSize)
                    {
                        StartReceiving(state);
                        return;
                    }

                    /*Check if there still are messages to be received.*/
                    if (receive == state.BufferSize)
                    {
                        StartReceiving(state);
                        return;
                    }

                    //sslstream has inconsistent buffers
                    StartReceiving(state);
                }
            }
            catch (Exception ex)
            {
                state.Reset();
                InvokeErrorThrown(ex);
                StartReceiving(state);
            }
        }
Exemplo n.º 5
0
 /// <summary>
 /// Löscht den verlassenen Client aus der Liste der Clients
 /// </summary>
 /// <param name="client">Der Client, zu dem die Verbindung verloren wurde</param>
 protected override void ConnectionLost(ClientInfo client)
 {
     Log("Client " + client.Name + " has left");
     OnClientLeft(client);
     ConnectedClients.Remove(client.ClientID);
     OnClientsChanged();
 }
Exemplo n.º 6
0
        void PacketHandler(IDataPacket dataPacket, ref Data data)
        {
            switch (dataPacket.ConnectionType)
            {
            case ConnectionType.Client:
                Logger.Instance.Log("ConnectionType is [Client]");
                var clientData = (ClientDataPacket)dataPacket;
                clientData.Servers = GetServers(clientData.Offset);
                data.TcpClient.GetStream().Write(clientData.ToBytes(), 0, Packet.MAX_BYTE_LENGTH);
                break;

            case ConnectionType.Server:
                Logger.Instance.Log("ConnectionType is [Server]");
                var serverData = (ServerDataPacket)dataPacket;
                if (serverData.RemoveFromCollection)
                {
                    var temp = data;
                    Logger.Instance.Log($"Server {temp.ID} @ {serverData.IPv4} Removed from collection");
                    ConnectedClients.Remove(ConnectedClients.First(o => o.ID == temp.ID));
                    break;
                }
                data.IPv4     = serverData.IPv4;
                data.Name     = serverData.Name;
                data.Port     = serverData.Port;
                serverData.ID = data.ID;
                var bytes = serverData.ToBytes();
                data.TcpClient.GetStream().Write(bytes, 0, bytes.Length);
                break;

            case ConnectionType.Hub:
                Logger.Instance.Log("ConnectionType is [Hub]");
                break;
            }
        }
Exemplo n.º 7
0
 // Remove peer from guid.
 public void RemovePeer(Guid guid)
 {
     if (ConnectedClients.ContainsKey(guid))
     {
         ConnectedClients.Remove(guid);
     }
 }
        protected override void ReceiveCallback(IAsyncResult result)
        {
            var state = (ClientMetadata)result.AsyncState;

            state.MreTimeout.Set();
            try
            {
                //Check if client is still connected.
                //If client is disconnected, send disconnected message
                //and remove from clients list
                if (!IsConnected(state.Id))
                {
                    RaiseClientDisconnected(state, DisconnectReason.Unknown);
                    lock (ConnectedClients)
                    {
                        ConnectedClients.Remove(state.Id);
                    }
                }
                //Else start receiving and handle the message.
                else
                {
                    var receive = state.SslStream.EndRead(result);


                    if (receive > 0)
                    {
                        if (state.UnhandledBytes != null && state.UnhandledBytes.Length > 0)
                        {
                            receive += state.UnhandledBytes.Length;
                            state.UnhandledBytes = null;
                        }

                        if (state.Flag == 0)
                        {
                            if (state.SimpleMessage == null)
                            {
                                state.SimpleMessage = new SimpleMessage(state, this, Debug);
                            }
                            state.SimpleMessage.ReadBytesAndBuildMessage(receive);
                        }
                        else if (receive > 0)
                        {
                            state.SimpleMessage.ReadBytesAndBuildMessage(receive);
                        }
                    }

                    state.MreReceiving.Set();
                    state.MreRead.Set();
                }
            }
            catch (Exception ex)
            {
                state.Reset();
                RaiseLog(ex);
                RaiseLog("Error handling message from client with guid : " + state.Guid + ".");
                state.MreReceiving.Set();
                RaiseErrorThrown(ex);
                // Receive(state);
            }
        }
Exemplo n.º 9
0
 private void OnServiceLost(object sender, ResonanceDiscoveredServiceEventArgs <ResonanceSignalRDiscoveredService <DemoServiceInformation>, DemoServiceInformation> e)
 {
     InvokeUI(() =>
     {
         ConnectedClients.Remove(e.DiscoveredService.DiscoveryInfo);
     });
 }
Exemplo n.º 10
0
        /// <summary>
        /// This is the event handler attached to every client that is connected's MessageReceive event.
        /// This is where it checks if a client has sent the disconnetion code, and if so, disposes of them.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ConnectedClient_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            if (e.Message == TcpOptions.EndConnectionCode.ToString())
            {
                ConnectedClients.Remove(sender as Client);
                var eventargs = new ClientToggleEventArgs
                {
                    ConnectedClient = sender as Client,
                    Time            = DateTime.Now
                };
                ClientDisconnected?.Invoke(this, eventargs);
            }
            else
            {
                foreach (var response in Responses)
                {
                    var willTrigger = false;

                    switch (response.Mode)
                    {
                    case ContentMode.Contains:
                        if (e.Message.Contains(response.Content))
                        {
                            willTrigger = true;
                        }
                        break;

                    case ContentMode.EndsWish:
                        if (e.Message.EndsWith(response.Content))
                        {
                            willTrigger = true;
                        }
                        break;

                    case ContentMode.StartsWith:
                        if (e.Message.StartsWith(response.Content))
                        {
                            willTrigger = true;
                        }
                        break;

                    case ContentMode.Equals:
                        if (e.Message == response.Content)
                        {
                            willTrigger = true;
                        }
                        break;
                    }

                    if (willTrigger)
                    {
                        response.Event?.Invoke(e);
                    }
                    else
                    {
                        MessageReceived?.Invoke(sender, e);
                    }
                }
            }
        }
        protected override void OnClientConnect(IAsyncResult result)
        {
            try
            {
                IClientMetadata state;
                int             id;

                lock (ConnectedClients)
                {
                    id = !ConnectedClients.Any() ? 1 : ConnectedClients.Keys.Max() + 1;

                    state = new ClientMetadata(((Socket)result.AsyncState).EndAccept(result), id);
                    CanAcceptConnections.Set();

                    ConnectedClients.Add(id, state);
                }

                //If the server shouldn't accept the IP do nothing.
                if (!IsConnectionAllowed(state))
                {
                    Log("A blacklisted ip tried to connect to the server: ipv4:" + state.RemoteIPv4 + " ipv6: " + state.RemoteIPv6);
                    lock (ConnectedClients)
                    {
                        ConnectedClients.Remove(id);
                    }
                    return;
                }

                Task.Run(() =>
                {
                    var stream = new NetworkStream(state.Listener);

                    //Create SslStream
                    state.SslStream = new SslStream(stream, false, AcceptCertificate);

                    var success = Authenticate(state).Result;

                    if (success)
                    {
                        RaiseClientConnected(state);
                        Receive(state);
                    }
                    else
                    {
                        lock (ConnectedClients)
                        {
                            ConnectedClients.Remove(id);
                        }
                        Log("Unable to authenticate server.");
                    }
                }, new CancellationTokenSource(10000).Token);
            }
            catch (Exception ex)
            {
                CanAcceptConnections.Set();
                RaiseLog(ex);
                RaiseErrorThrown(ex);
            }
        }
Exemplo n.º 12
0
 /// <summary>
 /// 类型:方法
 /// 名称:RemovePeer
 /// 作者:taixihuase
 /// 作用:删除一个客户端连接
 /// 编写日期:2015/7/12
 /// </summary>
 /// <param name="guid"></param>
 public void RemovePeer(Guid guid)
 {
     if (ConnectedClients.ContainsKey(guid))
     {
         ConnectedClientsToBroadcast.Remove(ConnectedClients[guid]);
         ConnectedClients.Remove(guid);
     }
 }
 private void OnSessionTerminated(SessionInfo sessionInfo)
 {
     Application.Current.Dispatcher.Invoke(() =>
     {
         var displayData = ConnectedClients.First(dd => dd.SessionId == sessionInfo.SessionId.ToString());
         ConnectedClients.Remove(displayData);
     });
 }
Exemplo n.º 14
0
        /// <summary>
        /// Remove a client.
        /// </summary>
        /// <param name="clientAddress">The target client's mac address.</param>
        public void RemoveClient(string clientAddress)
        {
            lock (ConnectedClients)
            {
                ConnectedClients.Remove(ConnectedClients.First(c => c.MacAddress == clientAddress));
            }

            // Keep the pending messages for this client. If it connects again, we want to be able to send the missing messages.
        }
Exemplo n.º 15
0
 private static void Disconnect(SocketClient client)
 {
     ConnectedClients.Remove(client.SocketId);
     ChatsClientMapping.Remove(client.SocketId);
     foreach (var chat in Chats)
     {
         chat.Value.Remove(client);
     }
 }
Exemplo n.º 16
0
        /// <summary>
        /// Client disconnected from the server
        /// </summary>
        /// <param name="DisconnectedClient">The client that has been disconnected</param>
        protected override void ClientDisconnected(ClientModel DisconnectedClient)
        {
            // Jump on the dispatcher thread
            var uiContext = SynchronizationContext.Current;

            uiContext.Send(x => ConnectedClients.Remove(DisconnectedClient), null);

            OnClientDisconnected(DisconnectedClient);
        }
Exemplo n.º 17
0
        protected override async void ReceiveCallback(IAsyncResult result)
        {
            var state = (ClientMetadata)result.AsyncState;

            try
            {
                //Check if client is still connected.
                //If client is disconnected, send disconnected message
                //and remove from clients list
                if (!IsConnected(state.Id))
                {
                    RaiseClientDisconnected(state);
                    lock (ConnectedClients)
                    {
                        ConnectedClients.Remove(state.Id);
                    }
                }
                //Else start receiving and handle the message.
                else
                {
                    var receive = state.Listener.EndReceive(result);

                    if (state.UnhandledBytes != null && state.UnhandledBytes.Length > 0)
                    {
                        receive += state.UnhandledBytes.Length;
                        state.UnhandledBytes = null;
                    }

                    //Does header check
                    if (state.Flag == 0)
                    {
                        if (state.SimpleMessage == null)
                        {
                            state.SimpleMessage = new SimpleMessage(state, this, Debug);
                        }
                        await ParallelQueue.Enqueue(() => state.SimpleMessage.ReadBytesAndBuildMessage(receive));
                    }
                    else if (receive > 0)
                    {
                        await ParallelQueue.Enqueue(() => state.SimpleMessage.ReadBytesAndBuildMessage(receive));
                    }

                    Receive(state, state.Buffer.Length);
                }
            }
            catch (Exception ex)
            {
                state.Reset();
                RaiseErrorThrown(ex);
                RaiseLog(ex);
                RaiseLog("Error handling message from client with guid : " + state.Guid + ".");
                Receive(state, state.Buffer.Length);
            }
        }
Exemplo n.º 18
0
        public void Disconnect(Client client)
        {
            client.NetworkStream.Write("disconnect");

            client.TcpClient.Client.Shutdown(SocketShutdown.Both);
            client.NetworkStream.Close();
            client.TcpClient.Close();

            ConnectedClients.Remove(client);

            ClientDisconnected?.Invoke(this, new ConnectionEventArgs(client));
        }
Exemplo n.º 19
0
 /// <summary>
 /// Disconnects a client node from this server
 /// </summary>
 /// <param name="client"></param>
 public void DisconnectNode(INetworkNode client)
 {
     if (ConnectedClients.ContainsKey(client))
     {
         if (client.Socket != null && client.Socket.Connected)
         {
             client.Socket.Disconnect(false);
             ConnectedClients[client].Abort();
         }
         ConnectedClients.Remove(client);
     }
 }
 private void OnClientDisconnected(SocketClientDisconnectedArgs args)
 {
     Console.WriteLine($"Client Disconnected, clientRemoteEndPoint : {args.DisconnectedSocketRemoteEndPoint}");
     lock (ConnectedClients)
     {
         if (ConnectedClients.Contains(args.DisconnectedClient))
         {
             ConnectedClients.Remove(args.DisconnectedClient);
         }
     }
     ClientDisconnected?.Invoke(args);
 }
        protected override void OnClientConnect(IAsyncResult result)
        {
            if (Token.IsCancellationRequested)
            {
                return;
            }

            CanAcceptConnections.Set();
            try
            {
                ISocketState state;

                lock (ConnectedClients)
                {
                    var id = !ConnectedClients.Any() ? 1 : ConnectedClients.Keys.Max() + 1;

                    state = new SocketState(((Socket)result.AsyncState).EndAccept(result), id);


                    //If the server shouldn't accept the IP do nothing.
                    if (!IsConnectionAllowed(state))
                    {
                        return;
                    }

                    var client = ConnectedClients.FirstOrDefault(x => x.Value == state);

                    if (client.Value == state)
                    {
                        id = client.Key;
                        ConnectedClients.Remove(id);
                        ConnectedClients.Add(id, state);
                    }
                    else
                    {
                        ConnectedClients.Add(id, state);
                    }

                    ClientConnectedInvoke(id, state);
                }

                StartReceiving(state);
            }
            catch (ObjectDisposedException ode)
            {
                InvokeErrorThrown(ode);
            }
            catch (SocketException se)
            {
                this.InvokeErrorThrown(se);
            }
        }
Exemplo n.º 22
0
 private void closeConnection(RServer server)
 {
     try
     {
         ConnectedClients.Remove(getOthIdOfClient(server)); //UNREGISTER CLIENT
         unRegisterPort(server.ServerPort);                 //UNREGISTER CLIENT PORT
         try { server.DetachClient(); }
         catch (Exception) { }
         try { server.StopListening(); }
         catch (Exception) { }
     }
     catch (Exception) { }
 }
Exemplo n.º 23
0
        public ServerViewModel(IWCFHostService hostService, IUnitOfWork db, ISettingsService settingsService, IDialogService dialogService)
        {
            this.hostService     = hostService;
            this.db              = db;
            this.settingsService = settingsService;
            this.dialogService   = dialogService;

            Client = new ChatWCFService.Client(settingsService.Name);
            Port   = settingsService.Port;
            hostService.ClientConnected += (s, e) =>
            {
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    ConnectedClients.Add(e.Client);
                    Notifications.Add(new Notification($"Client {e.Client.Name} connected", DateTime.Now, NotificationType.ClientConnected));
                });
            };
            hostService.ClientDisconneced += (s, e) =>
            {
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    var client = ConnectedClients.Where(c => c.Name == e.Client.Name).FirstOrDefault();
                    ConnectedClients.Remove(client);
                    Notifications.Add(new Notification($"Client {e.Client.Name} disconnected", DateTime.Now, NotificationType.ClientDisconnected));
                });
            };
            hostService.MessageReceived += (s, e) =>
            {
                DispatcherHelper.CheckBeginInvokeOnUI(() => {
                    Messages?.Add(new Model.Message(e.Message));
                });
            };

            DispatcherHelper.RunAsync(async() =>
            {
                var messages = (await db.Messages.GetAll()).Select(m => new Model.Message(m));
                foreach (var message in messages)
                {
                    Messages.Add(message);
                }
            });
            Messenger.Default.Register <NotificationMessage>(this, (m) => {
                switch (m.Notification)
                {
                case "ServerWindowClosed": StopServer(); break;
                }
            });
        }
 private void PacketHandlerLoop()
 {
     while (!_stopping)
     {
         NewPacketStruct packetStruct;
         while (_newPackets.TryDequeue(out packetStruct))
         {
             var  stream       = new BitStream(packetStruct.Data);
             uint type         = 0;
             uint connectionId = 0;
             stream.ReadBasicHeader(ref type, ref connectionId);
             Console.WriteLine("[NetworkingServer] handling packet received from " + packetStruct.From.ToString() + ", connection id: " + connectionId + ", packet type: " + Convert.ToString((PacketType)type));
             if (type == 0)
             {
                 Console.WriteLine("[NetworkingServer] skipping invalid packet");
                 continue;
             }
             if (type == 1)
             {
                 var par2       = stream.ReadBits(32);
                 var version    = stream.ReadBits(32);
                 var punkbuster = stream.ReadBits(1);
                 var unk        = stream.ReadBits(32);
                 var pass       = stream.ReadString(32).Replace("\0", "");
                 var mod        = stream.ReadString(32).Replace("\0", "");
                 if (mod != Config.ModName)
                 {
                     SendConnectDenied(packetStruct.From, 0x24);
                 }
                 ConnectionId++;
                 var client = new NetworkingClient(this, packetStruct.From, ConnectionId);
                 if (ConnectedClients.ContainsKey(packetStruct.From))
                 {
                     ConnectedClients.Remove(packetStruct.From);
                 }
                 ConnectedClients.Add(packetStruct.From, client);
                 SendConnectAccept(packetStruct.From, ConnectionId);
                 continue;
             }
             if (!ConnectedClients.ContainsKey(packetStruct.From))
             {
                 continue;
             }
             ConnectedClients[packetStruct.From].Handle((PacketType)type, stream);
         }
         Thread.Sleep(1);
     }
 }
Exemplo n.º 25
0
        private async Task HandleClientAsync(TcpClient client)
        {
            //TODO
            while (client.Connected)
            {
                string data = await ReadData(client);

                if (data != null)
                {
                    HandleData(data, client);
                }
            }
            await NotifyClientsOfUserLeft(client);

            ConnectedClients.Remove(client);
            ClientIDs.Remove(client);
        }
Exemplo n.º 26
0
        private void WatchClients()
        {
            while (Listen)
            {
                Thread.Sleep(new TimeSpan(0, 1, 0)); //check the servers every 1 minute
                ConnectedClients.AsParallel().ForAll(o => {
                    try {
                        if (o.TcpClient?.Client != null && o.TcpClient.Client.Connected)
                        {
                            /* pear to the documentation on Poll:
                             * When passing SelectMode.SelectRead as a parameter to the Poll method it will return
                             * -either- true if Socket.Listen(Int32) has been called and a connection is pending;
                             * -or- true if data is available for reading;
                             * -or- true if the connection has been closed, reset, or terminated;
                             * otherwise, returns false
                             */

                            // Detect if client disconnected
                            if (o.TcpClient.Client.Poll(0, SelectMode.SelectRead))
                            {
                                byte[] buff = new byte[1];
                                if (o.TcpClient.Client.Receive(buff, SocketFlags.Peek) == 0)
                                {
                                    // Client disconnected
                                    ConnectedClients.Remove(o);
                                    o.TcpClient.Close();
                                }
                            }
                        }
                        else
                        {
                            ConnectedClients.Remove(o);
                            o.TcpClient?.Close();
                        }
                    }
                    catch {
                        ConnectedClients.Remove(o);
                        o.TcpClient?.Close();
                    }
                });

                Thread.Sleep(16);
            }
        }
        /// <summary>
        /// Handle the "logout" command
        /// </summary>
        /// <param name="response">Message object to send to the user</param>
        private void HandleLogoutCommand(Message response)
        {
            if (_user == null)
            {
                response.Type    = MessageType.Error;
                response.Content = "Cannot log out: you are not logged in.";
                return;
            }

            // Remove user from list of connected clients
            ConnectedClients.Remove(_user);

            _user.LastSeenAt = DateTime.UtcNow;
            UserService.Update(_user.Id, _user);

            _user            = null;
            response.Type    = MessageType.Info;
            response.Content = "Logged out.";
        }
Exemplo n.º 28
0
        /// <summary>
        /// Sends the next instruction from the outgoing-queue.
        /// </summary>
        protected override void AsyncInstructionSendNext()
        {
            base.AsyncInstructionSendNext();

            if (!HandlerData.HaltActive)
            {
                try
                {
                    if ((HandlerData.OutgoingInstructions[0].Receiver as NetComCData).Authenticated ||
                        HandlerData.OutgoingInstructions[0].GetType() != typeof(InstructionLibraryEssentials.KeyExchangeServer2Client) ||
                        HandlerData.OutgoingInstructions[0].GetType() != typeof(InstructionLibraryEssentials.AuthenticationServer2Client))
                    {
                        Socket current = HandlerData.OutgoingInstructions[0]?.Receiver.LocalSocket;
                        byte[] data;

                        data = Encoding.UTF8.GetBytes(HandlerData.OutgoingInstructions[0].Encode());

                        try
                        {
                            current.Send(data);
                        }
                        catch (Exception)
                        {
                            Handler.Debug("Client disconnected > Connection lost. (101)", DebugType.Warning);
                            current.Close();
                            UserGroups.Disconnect(current);
                            ConnectedClients.Remove(current);
                            return;
                        }

                        Handler.Debug($"Sent Message to {HandlerData.OutgoingInstructions[0].Receiver.ToString()}.", DebugType.Info);
                        Handler.Debug(HandlerData.OutgoingInstructions[0].ToString(), DebugType.Info);
                        HandlerData.OutgoingInstructions.RemoveAt(0);
                    }
                    else
                    {
                        Handler.Debug($"Could not send Message to {HandlerData.OutgoingInstructions[0].Receiver.ToString()}. Authentication not valid.", DebugType.Error);
                        Handler.Debug($"Sending Authentication-Reminder...", DebugType.Info);

                        // Queues a authentication-reminder
                        Send(new InstructionLibraryEssentials.AuthenticationReminder(this, HandlerData.OutgoingInstructions[0].Receiver));

                        // moves the current instruction to the back
                        HandlerData.OutgoingInstructions.Add(HandlerData.OutgoingInstructions[0].Clone());
                        HandlerData.OutgoingInstructions.RemoveAt(0);
                    }
                }
                catch (Exception ex)
                {
                    Handler.Debug("Halting (08)", DebugType.Warning);
                    if (HandlerData.ShowExceptions)
                    {
                        Handler.Debug($"({ex.GetType().Name}) {ex.Message}", DebugType.Exception);
                    }
                    if (HandlerData.TryRestartOnCrash)
                    {
                        HaltAllThreads();
                    }
                }
            }
            else
            {
                Handler.Debug("Could not send message. Server is in halt-mode. Waiting for 5 seconds...", DebugType.Error);
                Thread.Sleep(5000);
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Gets called when a message is received.
        /// </summary>
        /// <param name="AR">IAsyncResult</param>
        private void ReceiveCallback(IAsyncResult AR)
        {
            try
            {
                Socket current = (Socket)AR.AsyncState;
                int    received;

                try
                {
                    received = current.EndReceive(AR);
                }
                catch (SocketException)
                {
                    Handler.Debug("Client disconnected > Connection lost. (102)", DebugType.Warning);
                    // Don't shutdown because the socket may be disposed and its disconnected anyway.
                    current.Close();
                    UserGroups.Disconnect(current);
                    ConnectedClients.Remove(current);
                    return;
                }

                byte[] recBuf = new byte[received];
                Array.Copy(buffer, recBuf, received);
                string text = Encoding.UTF8.GetString(recBuf);

                Console.ForegroundColor = ConsoleColor.Cyan;
                //Debug("Received message: " + text);
                Handler.Debug("Received message.", DebugType.Info);
                Console.ForegroundColor = ConsoleColor.White;

                InstructionBase[] instructionList = null;

                try
                {
                    instructionList = InstructionOperations.Parse(this, current, text, ConnectedClients).ToArray();

                    // Check for group-Addignment
                    foreach (InstructionBase instr in instructionList)
                    {
                        HandlerData.IncommingInstructions.Add(instr);

                        if (instr.GetType() != typeof(InstructionLibraryEssentials.KeyExchangeClient2Server) && !GroupAddRecords.Contains(instr.Sender.Username))
                        {
                            GroupAddRecords.Add(instr.Sender.Username);
                            UserGroups.TryGroupAdd(instr.Sender);
                        }
                    }
                }
                catch (NetComAuthenticationException ex)
                {
                    Handler.Debug("Authentication-Error (Instruction-Parsing).", DebugType.Error);
                    if (HandlerData.ShowExceptions)
                    {
                        Handler.Debug($"({ex.GetType().Name}) {ex.Message}", DebugType.Exception);
                    }
                }
                catch (Exception ex)
                {
                    Handler.Debug($"Error occured (Instruction-Parsing). ({HandlerData.LogErrorCounter})", DebugType.Error);
                    if (HandlerData.ShowExceptions)
                    {
                        Handler.Debug($"({ex.GetType().Name}) {ex.Message}", DebugType.Exception);
                    }
                    HandlerData.LogErrorCounter++;
                }



                try
                {
                    current.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, current);
                }
                catch (SocketException)
                {
                    Handler.Debug("Client disconnected > Connection lost. (103)", DebugType.Warning);
                    // Don't shutdown because the socket may be disposed and its disconnected anyway.
                    current.Close();
                    UserGroups.Disconnect(current);
                    ConnectedClients.Remove(current);
                    return;
                }
            }
            catch (Exception ex)
            {
                Handler.Debug("Halting (05)", DebugType.Warning);
                if (HandlerData.ShowExceptions)
                {
                    Handler.Debug($"({ex.GetType().Name}) {ex.Message}", DebugType.Exception);
                }
                if (HandlerData.TryRestartOnCrash)
                {
                    HaltAllThreads();
                }
            }
        }
Exemplo n.º 30
0
 protected void OnClientDisconnected(PaceClient client)
 {
     ConnectedClients.Remove(client);
     ClientDisconnected?.Invoke(this, new ClientEventArgs(client));
 }