Пример #1
0
 public void mainServer_StatusChanged(object sender, StatusChangedEventArgs e)
 {
     // Call the method that updates the form
     try
     {
         this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { e.EventMessage });
     }
     catch
     {
     }
 }
Пример #2
0
        // Отправить сообщение от админа
        public static void SendAdminMessage(string Message)
        {
            e = new StatusChangedEventArgs("Administrator: " + Message);
            OnStatusChanged(e);

            Socket[] sockets = new Socket[htUsers.Count];
            ChatServer.htUsers.Values.CopyTo(sockets, 0);
            for (int i = 0; i < sockets.Length; i++)
            {
                if (Message.Trim() == "" || !sockets[i].Connected || sockets[i] == null)
                {
                    continue;
                }
                try { sockets[i].Send(Encoding.Unicode.GetBytes("Administrator: " + Message)); }
                catch { sockets[i].Close(); RemoveUser(sockets[i]); }
            }
        }
Пример #3
0
        public void StartListening()
        {
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try { serverSocket.Bind(new IPEndPoint(IPAddress.Any, port)); }
            catch (Exception ex)
            {
                e = new StatusChangedEventArgs(ex.Message);
                OnStatusChanged(e);
                return;
            }
            // Запускаем listener'а
            serverSocket.Listen(20);
            ServRunning = true;

            // Запускаем новый поток, хостящий listener'а
            thrListener = new Thread(KeepListening);
            thrListener.IsBackground = true;
            thrListener.Start();
        }
Пример #4
0
        // Send messages from one user to all the others
        public static void SendMessage(string From, string Message)
        {
            StreamWriter swSenderSender;

            // First of all, show in our application who says what
            e = new StatusChangedEventArgs(From + " says: " + Message + "\r\n=================****===****===****====================");
            OnStatusChanged(e);


            // Create an array of TCP clients, the size of the number of users we have
            TcpClient[] tcpClients = new TcpClient[ChatServer.htUsers.Count];
            // Copy the TcpClient objects into the array
            ChatServer.htUsers.Values.CopyTo(tcpClients, 0);
            // Loop through the list of TCP clients
            for (int i = 0; i < tcpClients.Length; i++)
            {
                // Try sending a message to each
                try
                {
                    // If the message is blank or the connection is null, break out
                    if (Message.Trim() == "" || tcpClients[i] == null)
                    {
                        continue;
                    }

                    // Don't send the message to the same user.
                    //string kk = ((string)ChatServer.htConnections[tcpClients[i]]);
                    //string.Equals(kk, From);



                    // Send the message to the current user in the loop
                    swSenderSender = new StreamWriter(tcpClients[i].GetStream());
                    swSenderSender.WriteLine(From + '|'.ToString() + Message);
                    swSenderSender.Flush();
                    swSenderSender = null;
                }
                catch // If there was a problem, the user is not there anymore, remove him
                {
                    RemoveUser(tcpClients[i]);
                }
            }
        }
Пример #5
0
        // Обычная отправка сообщения
        public static void SendMessage(string From, string Message)
        {
            e = new StatusChangedEventArgs(DateTime.Now + " | " + From + " says: " + Message);
            OnStatusChanged(e);

            Socket[] sockets = new Socket[htUsers.Count];
            ChatServer.htUsers.Values.CopyTo(sockets, 0);
            string historyString = DateTime.Now + " | " + From + " says: " + Message;

            AddToHistory(historyString);
            for (int i = 0; i < sockets.Length; i++)
            {
                if (Message.Trim() == "" || sockets[i] == null)
                {
                    continue;
                }
                try { sockets[i].Send(Encoding.Unicode.GetBytes(DateTime.Now + " | " + From + " says: " + Message)); }
                catch { sockets[i].Close(); RemoveUser(sockets[i]); return; }
            }
        }
Пример #6
0
        // Envia mensagens administrativas
        public static void EnviaMensagemAdmin(string Mensagem)
        {
            StreamWriter swSenderSender;

            // Exibe primeiro na aplicação
            e = new StatusChangedEventArgs("Administrador: " + Mensagem);
            OnStatusChanged(e);

            // Cria um array de clientes TCPs do tamanho do numero de clientes existentes
            TcpClient[] tcpClientes = new TcpClient[Servidor.htUsuarios.Count];
            // Copia os objetos TcpClient no array
            Servidor.htUsuarios.Values.CopyTo(tcpClientes, 0);

            // Percorre a lista de clientes TCP
            for (int i = 0; i < tcpClientes.Length; i++)
            {
                // Tenta enviar uma mensagem para cada cliente
                try
                {
                    // Se a mensagem estiver em branco ou a conexão for nula sai...
                    if (Mensagem.Trim() == "" || tcpClientes[i] == null)
                    {
                        continue;
                    }

                    // Envia a mensagem para o usuário atual no laço
                    swSenderSender = new StreamWriter(tcpClientes[i].GetStream());
                    swSenderSender.WriteLine("Administrador: " + Mensagem);
                    swSenderSender.Flush();
                    swSenderSender = null;
                }
                catch
                {
                    // Se houver um problema , o usuário não existe , então remove-o
                    RemoveUsuario(tcpClientes[i]);
                }
            }
        }
Пример #7
0
        // Отправляем сообщения от одного пользователя всем остальным
        public static void SendMessage(string From, string Message)
        {
            StreamWriter swSenderSender;

            // Прежде всего, покажем в нашем приложении, кто что говорит
            e = new StatusChangedEventArgs(From + " говорит: " + Message);
            OnStatusChanged(e);

            // Создаем массив TCP-клиентов, размер которого соответствует количеству имеющихся у нас пользователей
            TcpClient[] tcpClients = new TcpClient[ChatServer.htUsers.Count];
            //Скопируем объекты TcpClient в массив
            ChatServer.htUsers.Values.CopyTo(tcpClients, 0);
            // Циклический просмотр списка TCP-клиентов
            for (int i = 0; i < tcpClients.Length; i++)
            {
                // Попробуйте отправить сообщение каждому из них
                try
                {
                    // Если сообщение пустое или соединение нулевое, просто пропускаем

                    if (Message.Trim() == "" || tcpClients[i] == null)
                    {
                        continue;
                    }
                    // Если сообщение пустое или соединение нулевое, вырывайтесь
                    swSenderSender = new StreamWriter(tcpClients[i].GetStream());
                    swSenderSender.WriteLine(From + " говорит: " + Message);
                    swSenderSender.Flush();
                    swSenderSender = null;
                }
                catch // Если возникла проблема, то пользователя там больше нет, удалите его
                {
                    RemoveUser(tcpClients[i]);
                }
            }
        }
Пример #8
0
 public void mainServer_StatusChanged(object sender, StatusChangedEventArgs e)
 {
     // Вызываем метод, который обновляет форму
     this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { e.EventMessage });
 }
Пример #9
0
 public void mainServer_StatusChanged(object sender, StatusChangedEventArgs e)
 {
     // Вызов метода обновления статуса
     this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { e.EventMessage });
 }
Пример #10
0
 public void mainServer_StatusChanged(object sender, StatusChangedEventArgs e)
 {
     // Call the method that updates the form
     this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { e.EventMessage });
 }
Пример #11
0
        public static void SendMessage(string From, string Message)
        {
            StreamWriter swSenderSender;

            e = new StatusChangedEventArgs(From + ": " + Message);
            OnStatusChanged(e);

            TcpClient[] tcpClients = new TcpClient[Server.htUsers.Count];
            Server.htUsers.Values.CopyTo(tcpClients, 0);

            for (int i = 0; i < tcpClients.Length; i++)
            {
                try
                {

                    if (Message.Trim() == "" || tcpClients[i] == null)
                    {
                        continue;
                    }

                    swSenderSender = new StreamWriter(tcpClients[i].GetStream());
                    swSenderSender.WriteLine(From + ": " + Message);
                    swSenderSender.Flush();
                    swSenderSender = null;
                }
                catch
                {
                    RemoveUser(tcpClients[i]);
                }
            }
        }
Пример #12
0
 public void mainServidor_StatusChanged(object sender, StatusChangedEventArgs e)
 {
     // Chama o método que atualiza o formulário
     this.Invoke(new AtualizaStatusCallback(this.AtualizaStatus), new object[] { e.EventMessage });
 }
Пример #13
0
        // Send messages from one user to all the others
        public static void SendMessage(string From, string Message)
        {
            StreamWriter swSenderSender;

            // First of all, show in our application who says what
            e = new StatusChangedEventArgs(From + " says: " + Message);
            OnStatusChanged(e);

            // Create an array of TCP clients, the size of the number of users we have
            TcpClient[] tcpClients = new TcpClient[ChatServer.htUsers.Count];
            // Copy the TcpClient objects into the array
            ChatServer.htUsers.Values.CopyTo(tcpClients, 0);
            // Loop through the list of TCP clients
            for (int i = 0; i < tcpClients.Length; i++)
            {
                // Try sending a message to each
                try
                {
                    // If the message is blank or the connection is null, break out
                    if (Message.Trim() == "" || tcpClients[i] == null)
                    {
                        continue;
                    }
                    // Send the message to the current user in the loop
                    swSenderSender = new StreamWriter(tcpClients[i].GetStream());
                    swSenderSender.WriteLine(From + " says: " + Message);
                    swSenderSender.Flush();
                    swSenderSender = null;
                }
                catch // If there was a problem, the user is not there anymore, remove him
                {
                    RemoveUser(tcpClients[i]);
                }
            }
        }
Пример #14
0
 // This is called when we want to raise the StatusChanged event
 public static void OnStatusChanged(StatusChangedEventArgs e)
 {
     StatusChangedEventHandler statusHandler = StatusChanged;
     if (statusHandler != null)
     {
         // Invoke the delegate
         statusHandler(null, e);
     }
 }
Пример #15
0
 // Реализация Status Changed события
 public static void OnStatusChanged(StatusChangedEventArgs e)
 {
     StatusChanged?.Invoke(null, e);
 }
Пример #16
0
 public static void OnStatusChanged(StatusChangedEventArgs e)
 {
     StatusChangedEventHandler statusHandler = StatusChanged;
     if (statusHandler != null)
     {
         statusHandler(null, e);
     }
 }
Пример #17
0
 public void mainServer_StatusChanged(object sender, StatusChangedEventArgs e)
 {
     this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { e.EventMessage });
 }