Ejemplo n.º 1
0
 void OnServerDisconnected(object sender, TimedEventArgs ea)
 {
     Trace.WriteLine("[OETS.Client] Соединение принудительно разорвано.");
 }
Ejemplo n.º 2
0
        //private static bool IsStart = true;
        void OnConnected(object sender, TimedEventArgs ea)
        {
            this.Dispatcher.Invoke(DispatcherPriority.Background, (Action)(() =>
            {

                if (client.IsConnected)
                {
                //    if (Choice.Instance.IsVisible)
                //        Choice.Instance.ProgressText.Content = "Связь с сервером установлена.";
                    Trace.WriteLine("[OETS.Client] Связь с сервером установлена.");
                }
                else
                {
                    Trace.WriteLine("[OETS.Client] Не возможно установить связь с сервером.");
                //    if (Choice.Instance.IsVisible)
                //        Choice.Instance.ProgressText.Content = "Не возможно установить связь с сервером.";
                }
            }));
        }
Ejemplo n.º 3
0
        void OnDisconnected(object sender, TimedEventArgs ea)
        {
            this.Dispatcher.Invoke(DispatcherPriority.Background, (Action)(() =>
            {
            //    if (Choice.Instance.IsVisible)
            //        Choice.Instance.ProgressText.Content = "Соединение разорвано.";
                Trace.WriteLine("[OETS.Client] Соединение разорвано.");
            }));

            UnSubscribeClientFromEvents();
            if (client.IsConnected)
                client.Disconnect();

            Thread.CurrentThread.IsBackground = true;
            Thread.Sleep(10000);
            ConnectClient();
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Remove the client from the server's list of clients.
        /// Events: ClientDisconnected
        /// </summary>
        private void OnClientManagerClientDisconnected(object sender, TimedEventArgs ea)
        {
            ClientManager cm = sender as ClientManager;
            if (cm == null)
                return;

            ClientKey clientKey = new ClientKey(cm.IPAddress, cm.Port);

            lock (clients.SyncRoot)
            {
                if (clients.Contains(clientKey))
                    clients.Remove(clientKey);

                if (ClientDisconnected != null)
                    ClientDisconnected(this, new ClientEventArgs(cm));

               }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// A command was received from the client. Process the command 
        /// and act as necessary.
        /// </summary>
        private void OnClientManagerCommandReceived(object sender, TimedEventArgs ea)
        {
            ClientManager cm = sender as ClientManager;
            if (cm == null)
                return;

            if (m_CommandHandler.ContainsKey(cm.SSocket.Command))
                m_CommandHandler[cm.SSocket.Command](cm, ea);
        }
Ejemplo n.º 6
0
        private void HandleCMSG_PONG(ClientManager cm, TimedEventArgs ea)
        {
            SSocket sSocket = cm.SSocket;
            if (!sSocket.Connected)
                return;

            try
            {
                PingPacket metadata = sSocket.Metadata as PingPacket;
                if (metadata != null)
                {
                    cm.IsPinged = metadata.Data.values;
                }
                else
                    cm.IsPinged = false;
                s_log.Trace("CMSG_PONG: {0} :: {1}", cm.ClientKey, metadata.Data.values.ToString());
            }
            catch (Exception exc)
            {
                LogUtil.ErrorException(exc, false, "HandleCMSG_PONG");
            }
            finally
            {
            }
        }
Ejemplo n.º 7
0
        private void HandleCMSG_REQUEST_USER_LOGIN(ClientManager cm, TimedEventArgs ea)
        {
            SSocket chatSocket = cm.SSocket;
            ResponsePacket pck = (ResponsePacket)chatSocket.Metadata;
            string error = string.Empty;
            bool alreadyLoggedIn = false;

            // set the name that the user choosed
            cm.UserName = pck.Response;

            if (cm.UserName.Length > 0)
            {
                cm.PingTimer.Change(10 * 1000, 10 * 1000);
                IEnumerator clientEnumerator = clients.GetEnumerator();
                // iterate through all users and check that there isn't another 
                // connection with the same user name 
                while (clientEnumerator.MoveNext())
                {
                    DictionaryEntry entry = (DictionaryEntry)clientEnumerator.Current;
                    ClientManager aClient = (ClientManager)entry.Value;

                    if (aClient.UserName == cm.UserName && !aClient.Equals(cm))
                    {
                        if (LoginFailed != null)
                            LoginFailed(this, new ClientEventArgs(cm, "Уже в сети!"));

                        alreadyLoggedIn = true;

                        cmToDisconnect.Enqueue(cm);
                        cm.SSocket.Sent += DisconnectAfterSend;

                        SendError(cm, cm.UserName + " уже в сети", "LOGIN");

                        break;
                    }
                }

                if (!alreadyLoggedIn)
                {
                    cm.Authenticated = true;

                    s_log.Debug("Клиент " + cm.IPAddress + " был авторизирован");

                    if (LoginSuccess != null)
                        LoginSuccess(this, new ClientEventArgs(cm));

                    SendResponse(cm, OpcoDes.SMSG_USER_AUTHENTICATED, cm.UserName);
                }
            }
            else
            {
                if (LoginFailed != null)
                    LoginFailed(this, new ClientEventArgs(cm, "Клиент " + cm.ClientKey + " не зарегистрирован."));

                cmToDisconnect.Enqueue(cm);
                cm.SSocket.Sent += DisconnectAfterSend;
                SendError(cm, "Ваш компьютер не может получить доступ к новостному серверу.\nВозможные причины:\n1) Ваш IP адрес не зарегистрирован в программном комплексе.\n2) Вы сменили IP адрес.\n3) Вы нуб и Вам просто не везёт.", "AUTH");
            }
        }
Ejemplo n.º 8
0
        private void HandleCMSG_GETTING_JOURNAL_2(ClientManager cm, TimedEventArgs ea)
        {
            DictionaryB idList = new DictionaryB();

            try
            {
                SSocket sSocket = cm.SSocket;
                if (!sSocket.Connected)
                    return;

                ResponsePacket d = (ResponsePacket)sSocket.Metadata;
                string news = new Smc(Smc.ServiceProviderEnum.TripleDES).Decrypt(d.Response);

                s_log.Debug("CMSG_GETTING_JOURNAL_2: {0} :: {1}:[{2}]", cm.ClientKey, ea.EventTime, news.Split(';').Length.ToString()/* + "::" + d.Response*/);

                string[] IdNews = news.Split(';');
                for (int i = 0; i < IdNews.Length; ++i)
                {
                    if (IdNews[i] != "")
                    {
                        int _id = Convert.ToInt32(IdNews[i]);
                        idList[_id] = _id.ToString();
                    }
                }

                StringBuilder IDS = new StringBuilder();
                IEnumerator en = JournalManager.Instance.JournalData.OrderBy(x=>x.ID).GetEnumerator();
                while (en.MoveNext())
                {
                    var entry = en.Current as JournalContentData;
                    if (!idList.Contains(entry.ID))
                    {
                        IDS.Append(entry.ID + ";");
                        JournalPacket pck = new JournalPacket(entry);
                        SendCommand(cm, OpcoDes.SMSG_JOURNAL_ADD_SYNC, pck); 
                    }
                }
                SendResponse(cm, OpcoDes.SMSG_JOURNAL_SYNC_END, "SYNC_2");
                if (IDS.Length > 0)
                {
                    s_log.Trace("У клиента {0} :: Добавлены записи: [{1}]", cm.ClientKey, IDS.ToString());
                    IDS.Remove(0, IDS.Length);
                }
                IDS = null;
            }
            catch (Exception exc)
            {
                LogUtil.ErrorException(exc, false, "HandleCMSG_GETTING_JOURNAL_2");
            }
            finally
            {
            }
        }
Ejemplo n.º 9
0
        private void HandleCMSG_GETTING_JOURNAL(ClientManager cm, TimedEventArgs ea)
        {
            try
            {
                SSocket sSocket = cm.SSocket;
                if (!sSocket.Connected)
                    return;

                ResponsePacket d = (ResponsePacket)sSocket.Metadata;
                string news = new Smc(Smc.ServiceProviderEnum.TripleDES).Decrypt(d.Response);

                s_log.Debug("CMSG_GETTING_JOURNAL: {0} :: {1}:[{2}]", cm.ClientKey, ea.EventTime, news.Split(';').Length.ToString()/* + "::" + d.Response*/);
                
                string[] IdJournal = news.Split(';');
                for (int i = 0; i < IdJournal.Length; ++i)
                {
                    if (IdJournal[i] != "")
                    {
                        int _id = Convert.ToInt32(IdJournal[i].Split('-')[0]);
                        if (JournalManager.Instance.Contains(_id))
                        {
                            journal_contentData nct = JournalManager.Instance.FindByID(_id);

                            if (nct.ID > 0)
                            {
                                string md = IdJournal[i].Split('-')[1];
                                string pd = IdJournal[i].Split('-')[2];

                                if (string.IsNullOrEmpty(md) || md != nct.ModifyDate ||
                                    string.IsNullOrEmpty(pd) || pd != nct.Date)
                                {
                                    JournalPacket pck = new JournalPacket(nct);
                                    SendCommand(cm, OpcoDes.SMSG_JOURNAL_MODIFY_SYNC, pck);
                                    s_log.Trace("У клиента {0} :: Изменены записи: [{1}]", cm.ClientKey, _id);
                                }
                            }
                        }
                        else
                        {
                            ResponsePacket pck = new ResponsePacket("SocketServer", cm.UserName, _id.ToString());
                            SendCommand(cm, OpcoDes.SMSG_JOURNAL_REMOVE_SYNC, pck);
                            s_log.Trace("У клиента {0} :: Удалены записи: [{1}]", cm.ClientKey, _id);
                        }
                    }
                }
                SendResponse(cm, OpcoDes.SMSG_JOURNAL_SYNC_END, "SYNC_1");
            }
            catch (Exception exc)
            {
                LogUtil.ErrorException(exc, false, "HandleCMSG_GETTING_JOURNAL");
            }
        }
Ejemplo n.º 10
0
        private void HandleCMSG_SEND_JOURNAL_ENTRY(ClientManager cm, TimedEventArgs ea)
        {
            SSocket chatSocket = cm.SSocket;
            JournalPacket pck = (JournalPacket)chatSocket.Metadata;

            journal_contentData jd = pck.Data;
            if (JournalManager.Instance.Contains(jd.ID))
            {
                s_log.Info("Получили модифицированную запись с ID:" + jd.ID);
                JournalManager.Instance.Set(jd);

            }
            else if (JournalManager.Instance.Add(ref jd))
            {
                s_log.Info("Получили новую запись с ID:" + jd.ID);
            }

            JournalPacket data = new JournalPacket(jd);
            lock (clients.SyncRoot)
            {
                IEnumerator clientEnumerator = clients.GetEnumerator();
                while (clientEnumerator.MoveNext())
                {
                    DictionaryEntry entry = (DictionaryEntry)clientEnumerator.Current;
                    ClientManager c = (ClientManager)entry.Value;

                    SSocket ss = c.SSocket;
                    SendCommand(c, (pck.Data.ID != -1 ? OpcoDes.SMSG_JOURNAL_MODIFY : OpcoDes.SMSG_JOURNAL_ADD), data);
                }
            }
        }