Problema com while e stream

1 resposta
L
Estou com um problema com o seguinte código que deveria ser um simples messenger:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chat;

import java.awt.event.KeyEvent;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author Lucas
 */
public class Chat extends javax.swing.JFrame {
    ServerSocket serv;
    Socket s;
    ObjectInputStream input;
    ObjectOutputStream output;

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


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane4 = new javax.swing.JScrollPane();
        conversa = new javax.swing.JTextArea();
        digitacao = new javax.swing.JTextField();
        jMenuBar1 = new javax.swing.JMenuBar();
        conexao = new javax.swing.JMenu();
        conectar = new javax.swing.JMenuItem();
        esperar = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        conversa.setColumns(20);
        conversa.setEditable(false);
        conversa.setRows(5);
        jScrollPane4.setViewportView(conversa);

        digitacao.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                digitacaoKeyPressed(evt);
            }
        });

        conexao.setText("Conexão");

        conectar.setText("Conectar");
        conectar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                conectarActionPerformed(evt);
            }
        });
        conexao.add(conectar);

        esperar.setText("Esperar");
        esperar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                esperarActionPerformed(evt);
            }
        });
        conexao.add(esperar);

        jMenuBar1.add(conexao);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            .addComponent(digitacao)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(digitacao, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

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

    private void conectarActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            s = new Socket("localhost", 7070);
            System.out.println("CONECTADO");
            output = new ObjectOutputStream(s.getOutputStream());
            output.flush();
            System.out.println("CRIOU O OUTPUTSTREAM");
            input = new ObjectInputStream(s.getInputStream());
            System.out.println("CRIOU O INPUTSTREAM");
            esperando();
        } catch (UnknownHostException ex) {
            Logger.getLogger(Chat.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Chat.class.getName()).log(Level.SEVERE, null, ex);
        }
    }                                        

    private void esperarActionPerformed(java.awt.event.ActionEvent evt) {                                        
        
        try {
            serv = new ServerSocket(7070);
            System.out.println("ServerSocket criado aguardando conexao com cliente...");
            s = serv.accept();
            if(s.isConnected())
            System.out.println("CONEXAO COMPLETADA");
            output = new ObjectOutputStream(s.getOutputStream());
            output.flush();
            System.out.println("CRIOU O OUTPUTSTREAM");
            input = new ObjectInputStream(s.getInputStream());
            System.out.println("CRIOU O INPUTSTREAM");
            esperando();
        } catch (IOException ex) {
            Logger.getLogger(Chat.class.getName()).log(Level.SEVERE, null, ex);
        }
    }                                       

    private void digitacaoKeyPressed(java.awt.event.KeyEvent evt) {                                     
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            conversa.append("EU disse: \n" + digitacao.getText()+"\n\n");
            try {
                output.writeChars("O OUTRO disse:\n"+digitacao.getText());
            } catch (IOException ex) {
                Logger.getLogger(Chat.class.getName()).log(Level.SEVERE, null, ex);
            } 
            digitacao.setText(null);
        }
    }                                    
    public void esperando() throws IOException{
        String message = "CONECTADO COM SUCESSO\n";
        output.writeObject(message);
        output.flush();
            while(!s.isClosed()){
            try {
                message = (String) input.readObject();
                conversa.append(message);
                System.out.println(message);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(Chat.class.getName()).log(Level.SEVERE, null, ex);
            }
            }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Chat().setVisible(true);
            }
            
        });
    }
    // Variables declaration - do not modify                     
    public javax.swing.JMenuItem conectar;
    private javax.swing.JMenu conexao;
    private javax.swing.JTextArea conversa;
    private javax.swing.JTextField digitacao;
    private javax.swing.JMenuItem esperar;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane4;
    // End of variables declaration                   
}

O problema é no método esperando, pois se o mesmo nao tiver while envia e recebe os dados normalmente, porém com o mesmo o programa trava e não sei de outro modo que posso fazer para checar se chega algum Objeto.

Atenciosamente, lhc00.

1 Resposta

E

Um erro comum de quem vai mexer com a classe java.net.Socket é achar que você consegue detectar que um socket foi fechado pelo outro lado usando isClosed.

Esse método “isClosed” indica apenas que você chamou antes o método close sobre esse socket. Como não é esse o seu caso, então ele na prática não serve para nada. A documentação, como de praxe no Javadoc, não é muito clara a esse respeito.

Para detectar se o socket foi fechado no outro lado, deve-se tentar ler ou escrever alguma coisa e se você receber uma exceção é que o socket tem algum problema (por exemplo, foi fechado no outro lado).

Criado 10 de agosto de 2012
Ultima resposta 10 de ago. de 2012
Respostas 1
Participantes 2