Client travado?

2 respostas
G

Olá, pessoal do GUJ!

A partir de um código que foi postado aqui no GUJ, comecei o desenvolvimento do meu chat. O servidor tem um erro quando um client se conect. O client ele inicia, o servidor reconhece que ele se conectou, mas o GUI não é criado e a janela fica preta/branca (a do client), como se estivesse travada! Segue o erro do servidor, o que me parece um problema com os threads:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at Server.talk(Server.java:66)
        at Server.chat(Server.java:57)
        at Server.startServer(Server.java:41)
        at Server.onButtonClicked(Server.java:160)
        at Server.access$000(Server.java:26)
        at Server$2.actionPerformed(Server.java:131)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
        at java.awt.Component.processMouseEvent(Component.java:6267)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
        at java.awt.Component.processEvent(Component.java:6032)
        at java.awt.Container.processEvent(Container.java:2041)
        at java.awt.Component.dispatchEventImpl(Component.java:4630)
        at java.awt.Container.dispatchEventImpl(Container.java:2099)
        at java.awt.Component.dispatchEvent(Component.java:4460)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
        at java.awt.Container.dispatchEventImpl(Container.java:2085)
        at java.awt.Window.dispatchEventImpl(Window.java:2478)
        at java.awt.Component.dispatchEvent(Component.java:4460)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Código da thread do servidor:
private void listen(final InputStream inputStream)
    {
        new Thread(new Runnable() {
            DataInputStream ds = new DataInputStream(inputStream);
            public void run()
            {
                try
                {
                    while(true) {
                        int size = ds.readInt();
                        int cont = 0;
                        char[] chars = new char[size];
                        while (cont < size) {
                            chars[cont] = ds.readChar();
                            cont = cont + 1;
                        }

                        String str = new String(chars);
                        msgTextArea.append(": " + str);
                        line = str;
                    }
                } catch (IOException e)
                {
                    
                }
            }
        }).start();
    }
Código do client:
public class Client extends javax.swing.JFrame {

    Socket socket;
    String line;

    /** Creates new form Client */
    public Client() {
        initComponents();
    }

    private void startClient(String host, int port)
    {
        try
        {
            socket = new Socket();
            socket.connect(new InetSocketAddress(host, port));
            chat(socket);
        }
        catch (UnknownHostException e)
        {
            JOptionPane.showMessageDialog(this,
                "Erro na conexão - java.net.UnknownHostException",
                "Erro",
                JOptionPane.ERROR_MESSAGE);

            e.printStackTrace();
            System.exit(2);
        }
        catch (IOException e)
        {
            JOptionPane.showMessageDialog(this,
                "Erro na conexão - java.io.IOException",
                "Erro",
                JOptionPane.ERROR_MESSAGE);

            e.printStackTrace();
            System.exit(1);
        }
    }

    private void chat(Socket s) throws IOException
    {
        msgTextArea.append("Conectado com " + s.getRemoteSocketAddress() + "\n");
        listen(s.getInputStream());
        talk(s.getOutputStream());
    }

    /**
     * @param outputStream
     */
    private void talk(OutputStream outputStream) throws IOException
    {
        DataOutputStream output = new DataOutputStream(outputStream);
        while(true)
        {
            if(!line.equals("")) {
                output.writeInt(line.length());
                for (char ch : line.toCharArray())
                    output.writeChar(ch);
                output.flush();
                line = "";
            }
        }
    }

    /**
     * @param inputStream
     */
    private void listen(final InputStream inputStream)
    {
        DataInputStream ds = new DataInputStream(inputStream);

        try {
            while(true) {
                int size = ds.readInt();
                int cont = 0;
                char[] chars = new char[size];
                while (cont < size) {
                    chars[cont] = ds.readChar();
                    cont = cont + 1;
                }

                String str = new String(chars);
                msgTextArea.append(str);
                msgTextField.setText("");
            }
        } catch (IOException e) {

        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jSeparator1 = new javax.swing.JSeparator();
        jScrollPane1 = new javax.swing.JScrollPane();
        msgTextArea = new javax.swing.JTextArea();
        msgTextField = new javax.swing.JTextField();
        sendButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        msgTextArea.setColumns(20);
        msgTextArea.setRows(5);
        msgTextArea.setFocusable(false);
        jScrollPane1.setViewportView(msgTextArea);

        sendButton.setText("Enviar");
        sendButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendButtonClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(msgTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 290, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE)
                .addComponent(sendButton)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 335, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(3, 3, 3)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(msgTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(sendButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void sendButtonClicked(java.awt.event.ActionEvent evt) {                                   
        line = msgTextField.getText();
    }                                  

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
               Client c =  new Client();
               c.setVisible(true);
               c.startClient("127.0.0.1", 4360);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    public javax.swing.JTextArea msgTextArea;
    public javax.swing.JTextField msgTextField;
    public javax.swing.JButton sendButton;
    // End of variables declaration                   

}

Eu sei que é um pouco de c´´odigo de mais, mas se vocês puderes me ajudar, ficarei grato.

2 Respostas

lucasportela

Pelo erro já está dizendo que o método talk está recebendo null, ou seja, não está recebendo nenhum outputStream
ou então você esqueceu de instanciar algo.

G

Obrigado pela sua resposta, lucas!

Eu dei uma revisada no código, mas não achei nada de estranho! O que será que pode estar acontecendo?

Grato desde já,
Gustravo Borba.

Criado 5 de janeiro de 2011
Ultima resposta 5 de jan. de 2011
Respostas 2
Participantes 2