chatmulticast in java

Asked

Viewed 53 times

0

I have a small problem in this code below in java.

It’s a multicast chat

Main error is in the commented constructor.

import java.awt.event.KeyEvent;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author tanira
 */
public class EmissorReceptor extends javax.swing.JFrame {

    ArrayList<String> listaClientes = new ArrayList<>();
    private final int porta;
    private final String ip;
    InetAddress group;
    MulticastSocket s;


    //da erro nesse construtor, a causa eh os argumentos que se pede
    public EmissorReceptor(String ip, int Porta) {
        this.ip = ip;
        this.porta = Porta;
    }
    private EmissorReceptor() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public void Conecta(String ip, int porta) {
        try {
            //define o IP do grupo
            group = InetAddress.getByName(this.ip);
            //cria um socket com a porta expecificada
            s = new MulticastSocket(this.porta);
            //entra no grupo multicast
            s.joinGroup(group);
        } catch (IOException e) {
            System.out.println("Problemas ao conectar.");
        }
    }

    public void atualizaMsg(String msg) {
        this.jTAChat.append(msg + "\n");
    }

    public void limpaListaClientes() {
        this.jTAClientes.setText("");
    }

    public void atualizaClientes(String cliente) {
        if (!listaClientes.contains(cliente)) {
            listaClientes.add(cliente);//adicionar um novo cliente caso o nome dele nao esteja na lista dos clientes
        }
        for (int i = 0; i < listaClientes.size(); i++) {
            this.jTAClientes.append(listaClientes.get(i) + "\n");
        }

    }

    public void enviaMsg(String msg) {
        try {
            Conecta(this.ip, this.porta);
            //CRIA UM PACOTE DATAGRAMA
            DatagramPacket mensagem = new DatagramPacket(msg.getBytes(), msg.length(), group, porta);
            //ENVIA A MENSAGEM AO GRUPO MULTICAST
            s.send(mensagem);
        } catch (IOException e) {
            System.out.println("Problemas ao enviar mensagem.");
        }
    }

    public void recebeMsg(String msg) {
        Conecta(this.ip, this.porta);// se conecta ao grupo multicast para pode receber as mensagens
        new Thread() {//utiliza thread pra nao bloquear
            @Override
            @SuppressWarnings("empty-statement")
            public void run() {
                while (true) {
                    byte[] bufferRec = new byte[100];
                    DatagramPacket pacoteRec = new DatagramPacket(bufferRec, bufferRec.length);
                    try {
                        s.receive(pacoteRec);
                        bufferRec = pacoteRec.getData();
                        String msgRec = new String(bufferRec, 0, pacoteRec.getLength());
                        String msgRecebida= new String(bufferRec, 0, pacoteRec.getLength());

                        //trata a msg
                        msgRec = msgRec.toLowerCase(); //deixa tudo em minusculo                        
                        String ajustes = msgRec.replace("disse:", "");// retira o disse: para poder manusear o nick e a msg em si
                        String partes[] = ajustes.split(" ");//deve ficar partes[0]= NICK || partes[1]= msg

                        if (!listaClientes.contains(partes[0])) {
                            listaClientes.add(partes[1]);//adicionar um novo cliente caso AINDA o nome dele nao esteja na lista dos clientes
                            atualizaClientes(partes[1]);

                        } else if (partes[0].equals("sair")) {//caso o cliente queira sair retira o nome dlee da lista e mostra a nova no chat
                            listaClientes.remove(listaClientes.indexOf(partes[0]));
                            atualizaClientes(listaClientes);
                        }
                        //agora passa a msgRec pra tela no atualiza msg (chama o metodo)
                        atualizaMsg(msgRecebida);
                    } catch (IOException ex) {
                        Logger.getLogger(EmissorReceptor.class.getName()).log(Level.SEVERE, null, ex);
                        System.out.println("Problemas na thread receptora.");
                    }
                }
            }
        }.start();
    }

    /**
     * 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">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTAChat = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jTFIp = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTFNick = new javax.swing.JTextField();
        jBConectar = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jTFMensagem = new javax.swing.JTextField();
        jBEnviar = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTAClientes = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTAChat.setColumns(20);
        jTAChat.setRows(5);
        jScrollPane1.setViewportView(jTAChat);

        jLabel1.setText("IP Multicast:");

        jTFIp.setText("localhost");

        jLabel2.setText("Nick:");

        jBConectar.setText("Conectar");
        jBConectar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBConectarActionPerformed(evt);
            }
        });

        jLabel3.setText("Clientes:");

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

        jTAClientes.setColumns(20);
        jTAClientes.setRows(5);
        jScrollPane2.setViewportView(jTAClientes);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jTFMensagem)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jBEnviar))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 611, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(jTFIp, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel2)
                        .addGap(27, 27, 27)
                        .addComponent(jTFNick, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(36, 36, 36)
                        .addComponent(jBConectar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel3)
                        .addGap(88, 88, 88))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(9, 9, 9)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jTFIp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)
                            .addComponent(jTFNick, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jBConectar)
                            .addComponent(jLabel3))))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 380, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTFMensagem, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jBEnviar))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane2))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jBConectarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBConectarActionPerformed
        //o metodo conecta serve nesse caso principalmente pra salvar o IP do cliente ja que no envia msg ele chamara o
        //conecta novamente
        Conecta(this.jTFIp.getText(), 3456);//Nesse caso dar uma porta estatica
        //atualiza a lista cliente
        atualizaClientes(this.jTFNick.getText());
        //escreve uma msg no textAreaChat que um determinado usuario se conectou
        enviaMsg(this.jTFNick.getText() + " entrou.");
    }//GEN-LAST:event_jBConectarActionPerformed

    private void jBEnviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBEnviarActionPerformed
        enviaMsg(this.jTFNick.getText() + " disse: " + this.jTFMensagem.getText());

    }//GEN-LAST:event_jBEnviarActionPerformed
    private void jEnviarActionPerformed(java.awt.event.KeyEvent evt) throws IOException {

    }

    private void jTFMensagemKeyPressed(java.awt.event.KeyEvent evt) {
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            //para enviar msg apenas com Enter
            enviaMsg(this.jTFNick.getText() + " disse: " + this.jTFMensagem.getText());
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<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(EmissorReceptor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EmissorReceptor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EmissorReceptor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EmissorReceptor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new EmissorReceptor().setVisible(false);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBConectar;
    private javax.swing.JButton jBEnviar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTAChat;
    private javax.swing.JTextArea jTAClientes;
    private javax.swing.JTextField jTFIp;
    private javax.swing.JTextField jTFMensagem;
    private javax.swing.JTextField jTFNick;
    // End of variables declaration//GEN-END:variables
} 
  • Where’s the bug? Add the stack to the question.

  • //of the error in this constructor, the cause is the arguments that are asked public Emisseceptor(String ip, int Port) { this.ip = ip; this.port = Port; } private Emisseceptor() { throw new Unsupportedoperationexception("Not supported yet."); //To change body of generated methods, Choose Tools | Templates. }

  • Your code is not executable. The method recebeMsg has parameter pass error, correct there and edit the question.

  • yes I know it’s not executable, but what I want to help is in constructing the method Emissorreceptor that receives the ip and port

1 answer

1

Your code is not reproducible, but may I suggest that the cause of the error is here:

private EmissorReceptor() {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

You created a constructor without parameters (or your IDE probably generated it), making an exception for not being implemented. I believe you are using Netbeans, which usually creates methods automatically in this way.

In the main you do not pass any parameter for the constructor, then the class will invoke this and launch the exception.

java.awt.EventQueue.invokeLater(new Runnable() {
    @Override
    public void run() {
        new EmissorReceptor().setVisible(false);
    }
});

Or you pass the requested parameters in the other class constructor EmissorReceptor correctly in main and removes this default ai constructor, or take this exception release and implement an empty constructor.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.