public ClientEventArgs(ClientManager clientManager) : base() { this.clientManager = clientManager; }
public ClientEventArgs(ClientManager clientManager, object args) : base() { this.clientManager = clientManager; this.args = args; }
private void ProcessAccept(SocketAsyncEventArgs args) { try { Socket clientSocket = args.AcceptSocket; ClientManager cm = new ClientManager(ref clientSocket); lock (clients.SyncRoot) { cm.Disconnected += OnClientManagerClientDisconnected; cm.CommandReceived += OnClientManagerCommandReceived; clients[cm.ClientKey] = cm; } StartAccept(args); } catch (ObjectDisposedException exc) { LogUtil.ErrorException(exc, false, "ProcessAccept1"); } catch (SocketException exc) { LogUtil.ErrorException(exc, false, "ProcessAccept2"); } catch (Exception exc) { LogUtil.ErrorException(exc, false, "ProcessAccept3"); } }
/// <summary> /// Disconnects a ClientManager and removes it from the list of clients. /// </summary> private void DisconnectClientManager(ClientManager cm) { ClientKey clientKey = new ClientKey(cm.IPAddress, cm.Port); lock (clients.SyncRoot) { cm.Disconnect(); if (clients.Contains(clientKey)) clients.Remove(clientKey); } }
public void SendCommand(ClientManager cm, OpcoDes command, object metadata) { SSocket sSocket = cm.SSocket; if (sSocket == null) return; sSocket.Sent += new EventHandler(SignalMutexSent); //mutexSent = new AutoResetEvent(true); try { sSocket.Command = command; sSocket.Metatype = metadata.GetType().FullName; sSocket.Metadata = metadata; sSocket.Send(); mutexSent.WaitOne(); } catch (Exception exc) { Trace.Write(exc.Message); } finally { mutexSent.Set(); } sSocket.Sent -= new EventHandler(SignalMutexSent); }
public void PingTimerCallback(ClientManager cm) { try { cm.IsPinged = false; SSocket sSocket = cm.SSocket; if (!sSocket.Connected) return; ping_template data = new ping_template(DateTime.Now.ToString(), cm.IsPinged); PingPacket pck = new PingPacket(data); SendCommand(cm, OpcoDes.SMSG_PING, pck); s_log.Trace("SMSG_PING: {0} ", data.ToString(cm.IPEndPoint.ToString())); } catch (Exception exc) { LogUtil.ErrorException(exc, false, "m_PingTimerCallback"); } }
private void SendError(ClientManager cm, string msg, string category) { SSocket chatSocket = cm.SSocket; ErrorPacket pck = new ErrorPacket(msg, category); if (!chatSocket.Connected) return; SendCommand(cm, OpcoDes.SMSG_ERROR, pck); }
/// <summary> /// Using the ClientManager parameter send back a response to the client. /// </summary> private void SendResponse(ClientManager cm, OpcoDes command, string response) { SSocket sSocket = cm.SSocket; ResponsePacket pck = new ResponsePacket(); pck.From = "SSocketServer"; pck.To = cm.UserName; pck.Response = response; SendCommand(cm, command, pck); }
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 { } }
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"); } }
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 { } }
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"); } }
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); } } }