Client-Server Chat application with Sockets does not work

Asked

Viewed 730 times

7

I’m doing a project and I got to the communication part between the server and the client and I couldn’t get the output I wanted (image output).

The goal is for the server and client to communicate with each other. That is, to test this I type a user and if I press the online button that user name appears in the received messages. This method is not attached because it is well done.

The server is not working.

And can someone explain this NIMBUS (client class) generated by netbeans? I went to Eclipse, it’s supposed to be like this?

Output pretendido

CUSTOMER CLASS

public class Cliente {

    public static void main(String args[]) {

        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 e) {

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (javax.swing.UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new QuequeApp().setVisible(true);
            }
        });
    }
}

Server

public class Servidor {
    public static void main(String[] args) {
        SocketServidor socket_servidor = new SocketServidor();
    }
}

Socketcliente

public class SocketCliente {
    private Socket socket;
    private ObjectOutputStream output;

    public Socket conectar(){   
        try {
            this.socket = new Socket("localHost", 8080); 
            this.output = new ObjectOutputStream(socket.getOutputStream()); 
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 
        return socket;
    }

    public void enviar(MensagensChat mensagem){
        try {
            output.writeObject(mensagem);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    }

Socketserver

public class SocketServidor {
    private ServerSocket servidorSocket;
    private Socket socket;

    private Map<String, ObjectOutputStream> utilizadoresChat = new HashMap<String, ObjectOutputStream>();  

    public SocketServidor(){
        try {
            servidorSocket = new ServerSocket(8080);
            while(true){                            
                socket = servidorSocket.accept();           
                new Thread(new ListennerSocket(socket)).start();    
            }
        } catch (IOException e) {
            e.printStackTrace();
        }   
    }

    private class ListennerSocket implements Runnable {
        private ObjectOutputStream output;      
        private ObjectInputStream input;

        public ListennerSocket(Socket socket) {
            try {
                output = new ObjectOutputStream(socket.getOutputStream());
                input = new ObjectInputStream(socket.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        @Override
        public void run() {
            MensagensChat mensagem = null;

            try {
                while((mensagem = (MensagensChat) input.readObject() )!= null){ 
                    Accao accao = mensagem.getAccao(); 
                    if(accao.equals(Accao.ONLINE)){
                        conectar(mensagem, output);
                    }else if(accao.equals(Accao.OFFLINE)){

                    }else if(accao.equals(Accao.ENVIAR_UM)){

                    }else if(accao.equals(Accao.ENVIAR_TODOS)){

                    }else if(accao.equals(Accao.CONTACTOS_ONLINE)){

                    }
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        private void conectar(MensagensChat mensagem, ObjectOutputStream output){   
            enviar_para_um(mensagem, output);
        }

        private void enviar_para_um(MensagensChat mensagem, ObjectOutputStream output){
            try {
                output.writeObject(mensagem);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Mensagenschat class

public class MensagensChat implements Serializable {

private String nome;            
private String mensagem;    
private String nomeClienteReceptorMensagem;     
private Set<String> contactosOnline = new HashSet<String>();    
private Accao accao;                                


public String getNomeCliente() {
    return nome;
}
public void setNomeCliente(String nomeCliente) {
    this.nome = nomeCliente;
}
public String getTextoMensagem() {
    return mensagem;
}
public void setTextoMensagem(String textoMensagem) {
    this.mensagem = textoMensagem;
}
public String getNomeClienteMensagemReservada() {
    return nomeClienteReceptorMensagem;
}
public void setNomeClienteMensagemReservada(String nomeClienteMensagemReservada) {
    this.nomeClienteReceptorMensagem = nomeClienteMensagemReservada;
}
public Set<String> getContactosOnline() {
    return contactosOnline;
}
public void setContactosOnline(Set<String> contactosOnline) {
    this.contactosOnline = contactosOnline;
}
public Accao getAccao() {
    return accao;
}
public void setAccao(Accao accao) {
    this.accao = accao;
}
}

1 answer

4


Nimbus Look & Feel

The Nimbus is a cross-platform visual user interface (UI) implementation included in Java 6.

It is to be an evolution to the themes already existing in Swing and is really cuter than the others, besides presenting better resolution for being based on vectors and not on bitmaps.

The code with the loop in the method main class Cliente, iterates on existing Java themes and, if Nimbus is available, tries to activate it in the current program. It sounds strange, but this avoids some unexpected error if the theme is not present in the version of Java that is running. This technique appears variously, but is a commonly used convention type, regardless of whether to use an IDE.

Client - Server

I did the archaeological work of reconstituting some classes that weren’t posted. I don’t know exactly the code you have on the screen, but it seems that is simply missing the method to read the return.

For example, I haven’t seen anywhere where you get the server response. For example:

this.input = new ObjectInputStream(socket.getInputStream()); 

And then:

public MensagensChat ler() {
    try {
        return (MensagensChat) input.readObject();
    } catch (IOException | ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}

Code that works

The code below has been modified from the question and successfully tested. Note that you need to run the server first and then the client class.

Client

public class SocketCliente {
    private Socket socket;
    private ObjectOutputStream output;
    private ObjectInputStream input;

    public Socket conectar() {
        try {
            this.socket = new Socket("localHost", 8080);
            this.output = new ObjectOutputStream(socket.getOutputStream());
            this.input = new ObjectInputStream(socket.getInputStream());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return socket;
    }

    public void enviar(MensagensChat mensagem) {
        try {
            output.writeObject(mensagem);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public MensagensChat ler() {
        try {
            return (MensagensChat) input.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String args[]) {

        SocketCliente cliente = new SocketCliente();
        cliente.conectar();
        cliente.enviar(new MensagensChat(Accao.ONLINE, "eu mesmo"));
        MensagensChat retorno = cliente.ler();
        System.out.printf(retorno.getMensagem());


    }
}

Server

public class SocketServidor {
    private ServerSocket servidorSocket;
    private Socket socket;

    private Map<String, ObjectOutputStream> utilizadoresChat = new HashMap<String, ObjectOutputStream>();

    public SocketServidor() {
        try {
            servidorSocket = new ServerSocket(8080);
            while (true) {
                socket = servidorSocket.accept();
                new Thread(new ListennerSocket(socket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private class ListennerSocket implements Runnable {
        private ObjectOutputStream output;
        private ObjectInputStream input;

        public ListennerSocket(Socket socket) {
            try {
                output = new ObjectOutputStream(socket.getOutputStream());
                input = new ObjectInputStream(socket.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        @Override
        public void run() {
            MensagensChat mensagem = null;

            try {
                while ((mensagem = (MensagensChat) input.readObject()) != null) {
                    Accao accao = mensagem.getAccao();
                    if (accao.equals(Accao.ONLINE)) {
                        conectar(mensagem, output);
                    } else if (accao.equals(Accao.OFFLINE)) {

                    } else if (accao.equals(Accao.ENVIAR_UM)) {

                    } else if (accao.equals(Accao.ENVIAR_TODOS)) {

                    } else if (accao.equals(Accao.CONTACTOS_ONLINE)) {

                    }
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        private void conectar(MensagensChat mensagem, ObjectOutputStream output) {
            enviar_para_um(mensagem, output);
        }

        private void enviar_para_um(MensagensChat mensagem, ObjectOutputStream output) {
            try {
                output.writeObject(mensagem);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new SocketServidor();
    }
}
  • Thank you so much for the answer! Those classes you sent me if you modify them I get the problem solved?

  • I also added my Messaging Chat class here. It’s that I get errors in the Client class implemented by Voce! Thanks

  • If you import my Messaging Chat class and see the constructor of me errors because?

  • I added one more class, is that with the solution this gives me error in several points and I’m not even finding the solution can help me sff? You’re not even giving me the intended output

  • Another question I have is with your solution, I run the server and then the client, so that I have the Mains in the socketClient and socketServitor classes

Browser other questions tagged

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