Chat [RESOLVIDO]

2 respostas
pedroroxd

Pessoal, eu fiz (copiei de um livro) um chat em java... é tipo um messenger.
Tem A classe Server/Server Test (onde roda) e Client/Client Test.

[color=red]Client:[/color]
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Client extends JFrame {

    private JTextField enterField;
    private JTextArea displayArea;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    private String message = "";
    private String chatServer;
    private Socket client;

    //inicializa chatServer e configura a GUI
        public Client(String host) {
            super("Cliente");

            chatServer = host;

            enterField = new JTextField();
            enterField.setEditable(false);
            enterField.addActionListener(
                        new ActionListener() {

                             //envia a mensagem ao servidor
                             public void actionPerformed (ActionEvent event)
                             {
                                sendData(event.getActionCommand());
                                enterField.setText("");
                             }
                         }
                    );

                    add(enterField, BorderLayout.NORTH);

                    displayArea = new JTextArea();
                    add(new JScrollPane(displayArea), BorderLayout.CENTER);

                    setSize(300,150);
                    setVisible(true);
        }

        //conecta-se ao servidor e processa as mensagens a partir do servidor
        public void runClient()
        {
            try //conecta-se ao servidor,obtém fluxos, processa a conexão
            {
                connectToServer();
                getStreams();
                processConnection();
            }

                catch (EOFException eofException)
                {
                    displayMessage("\nClient terminated connection");
                }

            catch(IOException ioException) {
                ioException.printStackTrace();
            }

            finally
            {
                    closeConnection();
            }
            }

        //conecta-se ao servidor
            private void connectToServer() throws IOException {
                displayMessage("Attemping connection\n");

                client = new Socket(InetAddress.getByName(chatServer), 12345);

                displayMessage("\Connected to: " + client.getInetAddress().getHostName());
            }

            //obtém fluxos para enviar e receber dados
                private void getStreams() throws IOException
                {
                    output = new ObjectOutputStream(client.getOutputStream());
                    output.flush();

                    input = new ObjectInputStream(client.getInputStream());

                    displayMessage("\nGot I/O streams\n");
                }

                //processa a conexão com o servidor
                    private void processConnection() throws IOException {
                        setTextFieldEditable(true);

                        do //processa as mensagens enviadas do servidor
                        {
                            try //le e exibe a mensagem
                            {
                                message = (String) input.readObject();
                                displayMessage("\n+ message");
                            }

                            catch (ClassNotFoundException classNotFoundException)
                            {
                                displayMessage("\nUnknown objetct type received");
                            }
                        } while (!message.equals("SERVER>>> TERMINATE"));
                    }

                    //fecha os fluxos e o socket
                        private void closeConnection() {
                            displayMessage("\nClosing connection");
                            setTextFieldEditable(false);

                            try {
                                output.close();
                                input.close();
                                client.close();
                            }
                            catch (IOException ioException) {
                                ioException.printStackTrace();
                            }
                        }

                        //envia mensagem ao servidor
                            private void sendData(String message) {

                                try //envia o objeto ao servidor
                                {
                                    output.writeObject("MESA 01 >>" +message);
                                    output.flush();
                                    displayMessage("MESA 01 >>" +message);
                                }

                                catch (IOException ioException) {
                                    displayArea.append("\nError writing object");
                                }
                            }

                            //manipula a displayArea na thread de despacho de eventos
                                private void displayMessage(final String messageToDisplay) {
                                    SwingUtilities.invokeLater(

                                            new Runnable() {
                                                public void run()
                                                {
                                                    displayArea.append(messageToDisplay);
                                                    }
                                    }
                                            );
                                }


                                //manipula o enterField na thread de despacho de eventos
                                    public void setTextFieldEditable(final boolean editable)
                                    {
                                        SwingUtilities.invokeLater(
                                                new Runnable() {
                                                public void run()
                                                {
                                                    enterField.setEditable(editable);
                                                }
                                        }
                                                );

                                    }

}
[color=red]Client Test:[/color]
import javax.swing.JFrame;

public class ClientTest {
        public static void main (String args[]) {
            Client application;

            //se não houver nenhum argumento de linha de comando
                if (args.length == 0)
                    application = new Client("127.0.0.1");


                else
                    application = new Client(args[0]);

                     application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                     application.runClient();
        }
}

Eu abro o ServerTest e o ClientTest... Roda certinho consigo conversar entre os 2...
Agora eu quero rodar o Client quando eu clicar em um botão...
Como posso fazer isso?

2 Respostas

pedroroxd

PS: Eu ja coloquei esse código no botão:

Client k; k = new Client("127.0.0.1"); k.runClient();

Se o ServerTest não tiver aberto, aparece o Client certinho, falando que não ta conseguindo conexão…
Mas caso o ServerTest esteja aberto, ele abre o Client, so que ele fica “bugado” (Não aparece nada dentro dele, fica transparente).
Se eu rodar o ClientTest, sem ser dentro do botão dá certinho… Só no botão que fica “bugado”…

Qualqr ajuda é válida…
Vlw ae ;]

pedroroxd

Apaguei, fiz outro e funcionou…
Obrigado pela atenção :evil:

Criado 10 de setembro de 2009
Ultima resposta 26 de set. de 2009
Respostas 2
Participantes 1