Problemas no Servidor (Numero de Conexoes)

0 respostas
H

Olá amigos,
estou fazendo um programa bem simples usando sockets em java, é um cliente/servidor, melhor dizendo um bate-papo. Eu tenho um cliente ou vários (é só executar várias vezes o programa cliente) e então quando um cliente manda uma mensagem o servidor manda para todos os clientes.

Porém estou com problemas, o código ta compilando direitinho e ele manda mensagem para todo mundo, mas agora implementei uma nova funcionalidade que é CONTAR O NÚMERO DE CLIENTES CONECTADOS ao servidor. Sendo assim, eu conto direitinho o número de clientes que se conectam, porém não sei quando um cliente ENCERRA A CONEXÃO com o meu servidor, já vasculhei internet e tudo e nada de achar.

Abaixo segue o fonte do cliente, eu implementei nela a interface WindowListener para que quando o cliente feche a janela a conexão com o servidor seja fechada tb, porém ao fechar a janela tive vários EXCEPTION em sock.close() mas antes disso tudo esta ok, o programa manda mensagem pro server que manda pra todo mundo e o cliente recebe perfeitamente, o problemas esta apenas quando a janela é fechada.

import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class SimpleChatClient2 {
      JTextArea incoming;
      JTextField outgoing;
      BufferedReader reader;
      PrintWriter writer;
      Socket sock;

      public static void main(String[] args) {
             SimpleChatClient2 client = new SimpleChatClient2();
             client.go();
      } 

      public void go() {
             JFrame frame = new JFrame("Chat Cliente");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             //frame.addWindowListener(new FechamentodaJanela());
             JPanel mainPanel = new JPanel();
             incoming = new JTextArea(15,50);
             incoming.setLineWrap(true);
             incoming.setWrapStyleWord(true);
             incoming.setEditable(false);
             JScrollPane qScroller = new JScrollPane(incoming);
             qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
             qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
             outgoing = new JTextField(20);
             JButton sendButton = new JButton("Enviar");
             sendButton.addActionListener(new SendButtonListener());
             mainPanel.add(qScroller);
             mainPanel.add(outgoing);
             mainPanel.add(sendButton);
             setUpNetworking();

             Thread readerThread = new Thread(new IncomingReader());
             readerThread.start();

             frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
             frame.setSize(400,500);
             frame.setVisible(true);
             frame.addWindowListener(new FechamentodaJanela());
      }

      private void setUpNetworking() {
              try {
                  sock = new Socket("127.0.0.1", 5000);
                  InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
                  reader = new BufferedReader(streamReader);
                  writer = new PrintWriter(sock.getOutputStream());
                  System.out.println("Conexao Estabelecida");
              } catch (IOException ex) {
                      ex.printStackTrace();
              } 
      }

      class FechamentodaJanela implements WindowListener {
              
            public void windowClosed(WindowEvent e) {
                   
            }
               
            public void windowOpened(WindowEvent e) {
             
            }
                  
            public void windowIconified(WindowEvent e) {
               
            }
                 
            public void windowDeiconified(WindowEvent e) {
                  
            }
                
            public void windowActivated(WindowEvent e) {
              
            }
               
            public void windowDeactivated(WindowEvent e) {
               
            }
                
            public void windowGainedFocus(WindowEvent e) {
                 
            }
               
            public void windowLostFocus(WindowEvent e) {
                  
            }
                
            public void windowStateChanged(WindowEvent e) {
               
            }
                 
            public void windowClosing(WindowEvent e) {
                   System.out.println("FOI FECHADA");
                   //sock.close();

                   try {
                       sock.close();
                       System.out.println("Conexao Fechada");
                   } catch (IOException ex) {
                       //ex.printStackTrace();
                   } 
            }
        
      } 

      class SendButtonListener implements ActionListener {
            public void actionPerformed(ActionEvent ev) {
                   try {
                       writer.println(outgoing.getText());
                       writer.flush();
                   } catch (Exception ex) {
                           ex.printStackTrace();
                   }
                   outgoing.setText("");
                   outgoing.requestFocus();
            }
      }

      class IncomingReader implements Runnable {
            public void run() {
                   String message;
                   try {
                       while ((message = reader.readLine()) != null) {
                             System.out.println("read " + message);
                             incoming.append(message + "\n");
                       }
                   }
                   catch (Exception ex) { ex.printStackTrace(); }
            }
      }
}

E abaixo eu coloco o código do servidor, eu incremento a variavel "i" para indicar quantos clientes estão conectados, ou melhor, quando um cliente se conecta eu a incremento. Mas e como vou saber quando o cliente encerra a conexão?

import java.io.*;
import java.net.*;
import java.util.*;

/* Como este fonte usa certas coisas inseguras do java deve se usar a sintaxe
   javac -source 1.4 VerySimpleChatServer2.java
   para compilar este fonte.
*/

class VerySimpleChatServer2 {
      ArrayList clientOutputStreams;
      int i = 0;

      public class ClientHandler implements Runnable {
            BufferedReader reader;
            Socket sock;
                    
            public ClientHandler(Socket clientSocket) {
                   try {
                       sock = clientSocket;
                       InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
                       reader = new BufferedReader(isReader);
                   } catch (Exception ex) { 
                           //ex.printStackTrace();
                           System.out.println("Alguem saiu");
                   }
            }
                  
            public void run() {
                   String message;
                   try {
                       while ((message = reader.readLine()) != null) {
                             System.out.println("read " + message);
                             tellEveryone(message);
                       }
                   } catch (Exception ex) { ex.printStackTrace(); }
            }
      }

       public static void main(String[] args) {
              new VerySimpleChatServer2().go();
       }

       public void go() {
                   clientOutputStreams = new ArrayList();
                   try {
                       ServerSocket serverSock = new ServerSocket(5000);
                       while (true) {
                             ArrayList dados = new ArrayList();
                             Socket clientSocket = serverSock.accept();
                             PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
                             clientOutputStreams.add(writer);
                             Thread t = new Thread(new ClientHandler(clientSocket));
                             t.start();
                             System.out.println("Recebeu uma conexao");
                             i++;
                       }
                   } catch (Exception ex) {
                           //ex.printStackTrace();
                           System.out.println("Alguem saiu");
                   }
       }

       public void tellEveryone(String message) {
                   Iterator it = clientOutputStreams.iterator();
                   while (it.hasNext()) {
                         try {
                             PrintWriter writer = (PrintWriter) it.next();
                             writer.println(message);
                             writer.flush();
                             System.out.println("Temos "+i+" conexoes");
                         } catch (Exception ex) {
                                 //ex.printStackTrace();
                                 System.out.println("Alguem saiu");
                         }
                   }
       }
}

Se alguem puder ajudar fico muito agradecido.

Criado 20 de setembro de 2007
Respostas 0
Participantes 1