Exemple #1
0
        private void uiBtnLigarServidor_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(uiTxtIP.Text) || string.IsNullOrEmpty(uiTxtPorta.Text))
            {
                MessageBox.Show("Informe o endereço IP.");
                uiTxtIP.Focus();
                return;
            }

            try
            {
                // Analisa o endereço IP do servidor informado no textbox
                IPAddress enderecoIP = IPAddress.Parse(uiTxtIP.Text);

                // Cria uma nova instância do objeto ChatServidor
                mainServidor = new ChatServidor(enderecoIP, uiTxtPorta.Text);

                // Vincula o tratamento de evento StatusChanged a mainServer_StatusChanged
                ChatServidor.StatusChanged += new StatusChangedEventHandler(mainServidor_StatusChanged);

                // Inicia o atendimento das conexões
                mainServidor.IniciaAtendimento();

                // Mostra que nos iniciamos o atendimento para conexões
                txtDados.AppendText("#O SERVIDOR FOI INICIADO.\r\n");

                uiBtnLigarServidor.ButtonColor = Color.Orange;
                uiBtnLigarServidor.Enabled     = false;
                uiBtnLigarServidor.Text        = "O SERVIDOR ESTÁ EM EXECUÇÃO";
                btnAdmin.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ocorreu um erro na conexão: " + ex.Message);
                uiBtnLigarServidor.ButtonColor = Color.Red;
                uiBtnLigarServidor.Enabled     = true;
                uiBtnLigarServidor.Text        = "TENTAR NOVAMENTE...";
            }
        }
Exemple #2
0
        // Ocorre quando um novo cliente é aceito
        private void AceitaCliente()
        {
            srReceptor = new System.IO.StreamReader(tcpCliente.GetStream());
            swEnviador = new System.IO.StreamWriter(tcpCliente.GetStream());

            // Lê a informação da conta do cliente
            usuarioAtual = srReceptor.ReadLine();

            // temos uma resposta do cliente
            if (usuarioAtual != "")
            {
                // Armazena o nome do usuário na hash table
                if (ChatServidor.htUsuarios.Contains(usuarioAtual) == true)
                {
                    // 0 => significa não conectado
                    swEnviador.WriteLine("0|Este nome de usuário já existe.");
                    swEnviador.Flush();
                    FechaConexao();
                    return;
                }
                else if (usuarioAtual == "Administrator")
                {
                    // 0 => não conectado
                    swEnviador.WriteLine("0|Este nome de usuário é reservado.");
                    swEnviador.Flush();
                    FechaConexao();
                    return;
                }
                else
                {
                    // 1 => conectou com sucesso
                    swEnviador.WriteLine("1");
                    swEnviador.Flush();

                    // Inclui o usuário na hash table e inicia a escuta de suas mensagens
                    ChatServidor.IncluiUsuario(tcpCliente, usuarioAtual);
                }
            }
            else
            {
                FechaConexao();
                return;
            }
            //
            try
            {
                // Continua aguardando por uma mensagem do usuário
                while ((strResposta = srReceptor.ReadLine()) != "")
                {
                    // Se for inválido remove-o
                    if (strResposta == null)
                    {
                        ChatServidor.RemoveUsuario(tcpCliente);
                    }
                    else
                    {
                        // envia a mensagem para todos os outros usuários
                        ChatServidor.EnviaMensagem(usuarioAtual, strResposta);
                    }
                }
            }
            catch
            {
                // Se houve um problema com este usuário desconecta-o
                ChatServidor.RemoveUsuario(tcpCliente);
            }
        }