0 votos
por (20 puntos) en Java
Hola, mi duda es como crear un chat en java, he visto codigos en la red pero no les entiendo asi que podria alguien decirme como programo un chat, por que lo mas facil seria copiar y pegar pero como que no... podria alguien decirme programo un chat en Java con interfaz grafica [GUI], por lo que he leido necesito socket's, hilos, y manejo de flujos... pero de ahi no tengo la mas minima idea, ayuda!!!


12 Respuestas

0 votos
por (8.5k puntos)
Efectivamente necesitas sockets y algo de AWT o Swing (interfaces gráficas). La verdad es que del tema chat en Java hay bastantes tutoriales por internet.

Te paso uno muy bueno, muy conocido y en español:

http://www.chuidiang.com/java/sockets/hilos/socket_hilos.php

Aquí tienes otro en inglés:

http://www.ashishmyles.com/tutorials/tcpchat/index.html


0 votos
por (3.2k puntos)
Este es el codigo para el servidor:

=================================

import java.io.EOFException;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.net.ServerSocket;

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 Servidor extends JFrame{

    private JTextField campoEscritura;

    private JTextArea areaCharla;

    private ObjectOutputStream salida;

    private ObjectInputStream entrada;

    private ServerSocket servicio;

    private Socket conexion;

    private int contador;

    //Configuracion de GUI

    public Servidor(){

        super("Servidor");

        campoEscritura = new JTextField();

        campoEscritura.setEditable(false);

        campoEscritura.addActionListener(

            new ActionListener(){

                public void actionPerformed(ActionEvent e){

                    enviarDatos(e.getActionCommand());

                    campoEscritura.setText("");

                }

            }

        );

        add(campoEscritura, BorderLayout.SOUTH);

        areaCharla = new JTextArea();

        add(new JScrollPane(areaCharla), BorderLayout.CENTER);

        setSize(300,150);

        setVisible(true);

    }

    public void iniciarServidor(){

        try{

            servicio = new ServerSocket(12345, 100);

            while(true){

                try{

                    esperarConexion();

                    getFlujos();

                    procesarConexion();

                }catch(EOFException eof){

                    mostrarMensaje("Servidor termino la conexion");

                }finally{

                    cerrarConexion();

                    contador++;

                }

            }

        }catch(IOException io){

            io.printStackTrace();

        }

    }

    private void esperarConexion() throws IOException{

        mostrarMensaje("Esperando Conexiones");

        conexion = servicio.accept();

        mostrarMensaje("Conección "+contador+" recibida de: "+ conexion.getInetAddress().getHostName());

    }

    private void getFlujos() throws IOException{

        salida = new ObjectOutputStream(conexion.getOutputStream());

        salida.flush();

        entrada = new ObjectInputStream(conexion.getInputStream());

        mostrarMensaje("n Corren los Flujos de E/S n");

    }

    private void procesarConexion() throws IOException{

        String mensaje = "Conexion Establecida";

        enviarDatos(mensaje);

        setTextFieldEditable(true);

        do{

            try{

                mensaje = (String) entrada.readObject();

                mostrarMensaje("n"+mensaje);

            }catch(ClassNotFoundException cnfe){

                mostrarMensaje("n Tipo de Objeto desconocido fue recibido");

            }

        } while(!mensaje.equals("CLIENT>>> FINITO"));

    }

    private void cerrarConexion(){

        mostrarMensaje("nConexión cerradan");

        setTextFieldEditable(false);

        try{

            salida.close();

            entrada.close();

            conexion.close();

        } catch(IOException io){

            io.printStackTrace();

        }

    }

    private void enviarDatos(String mensaje){

        try{

            salida.writeObject("nSERVER>>> "+mensaje);

            salida.flush();

            mostrarMensaje("nSERVER>>> "+ mensaje);

        }

        catch(IOException io){

            areaCharla.append("nError al escribir el objeto");

        }

    }

    private void mostrarMensaje(final String mensajeAmostrar){

        SwingUtilities.invokeLater(

            new Runnable(){

                public void run(){

                    areaCharla.append(mensajeAmostrar);

                }

            }

        );

    }

    private void setTextFieldEditable(final boolean editable){

        SwingUtilities.invokeLater(

            new Runnable(){

                public void run(){

                    campoEscritura.setEditable(editable);

                }

            }

        );

    }

}


0 votos
por (3.2k puntos)
este el codigo para probar el Servidor:

========================================

import javax.swing.JFrame;

public class PruebaServidor{

   public static void main( String args[] ){

      Servidor servidor = new Servidor(); // create server

      servidor.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

      servidor.iniciarServidor(); // run server application

    } // end main

 }


0 votos
por (3.2k puntos)
Este el codigo para un Cliente para el chat

===========================================

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 Cliente extends JFrame{

    private JTextField campoTexto;

    private JTextArea areaCharla;

    private ObjectOutputStream output;

    private ObjectInputStream input;

    private String mensaje = "";

    private String ipServidor;

    private Socket cliente;

    public Cliente( String host ){

        super( "Cliente" );

        ipServidor = host;

        campoTexto = new JTextField();

        campoTexto.setEditable( false );

        campoTexto.addActionListener(

           new ActionListener(){

             public void actionPerformed( ActionEvent event ){

                 enviarDatos( event.getActionCommand() );

                 campoTexto.setText( "" );

              }

           }

        );

        add( campoTexto, BorderLayout.SOUTH );

        areaCharla = new JTextArea();

        add( new JScrollPane( areaCharla ), BorderLayout.CENTER );

        setSize( 300, 150 );

        setVisible( true );

     }

     public void correrCliente(){

        try{

           conectarAservidor();

           conseguirFlujo();

           procesarConexion();

        }catch ( EOFException eofException ) {

           mostrarMensaje( "nClient terminated connection" );

        }catch ( IOException ioException ){

           ioException.printStackTrace();

        }finally {

           cerrarConexion();

        }

     }

     private void conectarAservidor() throws IOException{

        mostrarMensaje( "Esperando conectarse" );

        cliente = new Socket( InetAddress.getByName( ipServidor ), 12346 );

        mostrarMensaje( "Connected to: " + cliente.getInetAddress().getHostName() );

     }

     private void conseguirFlujo() throws IOException {

        output = new ObjectOutputStream( cliente.getOutputStream() );

        output.flush();

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

        mostrarMensaje( "nExiste conexion con Servidorn" );

     }

     private void procesarConexion() throws IOException{

        setTextFieldEditable( true );

        do{

           try{

              mensaje = ( String ) input.readObject();

              mostrarMensaje( "n" + mensaje );

           }catch ( ClassNotFoundException classNotFoundException ){

              mostrarMensaje( "nUnknown object type received" );

           }

        } while ( !mensaje.equals( "SERVER>>> FINITO" ) );

    }

     private void cerrarConexion(){

        mostrarMensaje( "nCerrando la conexion" );

        setTextFieldEditable( false );

        try{

           output.close();

           input.close();

           cliente.close();

        }

        catch ( IOException ioException ){

           ioException.printStackTrace();

        }

     }

     private void enviarDatos( String sms )

     {

        try{

           output.writeObject( "CLIENTE>>> " + sms );

           output.flush();

           mostrarMensaje( "nCLIENTE>>> " + sms );

        }

       catch ( IOException ioException )

        {

           areaCharla.append( "nNo se puede enviar el mensaje" );

        }

     }

     private void mostrarMensaje( final String mensajeToDisplay ) {

        //SwingUtilities.invokeLater(

          // new Runnable()

           //{

             // public void run()

              //{

                 areaCharla.append( mensajeToDisplay );

              //}

           //}

        //);

     }

     private void setTextFieldEditable( final boolean editable )

     {

        SwingUtilities.invokeLater(

           new Runnable()

           {

              public void run() // sets campoTexto's editability

              {

                 campoTexto.setEditable( editable );

              }

           }

        );

     }

}


0 votos
por (3.2k puntos)
Este el codigo para ejecutar Cliente, recuerda que se hace uso de tu servidor interno LOCALHOST 127.0.0.1

===========================================

import javax.swing.JFrame;

public class ClientTest {

    public static void main( String args[] ) {

        Cliente cliente;

        cliente = new Cliente( "127.0.0.1" );

        cliente.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

        cliente.correrCliente();

    }

}


0 votos
por (3.2k puntos)
Para probar esto, es importante que primero ejecutes el Servidor, esto se debe a que se esta usando TCP, saludos :)

Espero sea de ayuda


0 votos
por (8.5k puntos)
fiurer87 veo que has entrado con fuerza en el foro, pero fíjate que el mensaje original tiene 6 meses de antigüedad, si es 6 meses no consiguio hacer un chat en Java, mal vamos jeje.

Un saludo


0 votos
por (3.2k puntos)
Gracias por la aclaracion.

Puse el ejemplo por que el hilo de la conversacion sigue activo, y como tengo el codigo para hacer lo que pedia, quiza pueda ayudar a otros ahora o en un futuro (si java sigue vigente para entonces). Asi que hilo abierto aunque pasadito siempre es una fuente de informacion para otros internautas.

Atte: Roberto


0 votos
por (1.4k puntos)
@Torres, @fiurer87,

Agradeceros a los dos vuestra amplia colaboración en el foro.

Muchas gracias.


0 votos
por (3.2k puntos)
Gracias Admin, pero soy fiurer87  no  figure87.


Preguntas relacionadas

0 votos
2 respuestas
0 votos
5 respuestas
preguntado por jeremias10 (760 puntos) Ene 28, 2016 en Java
0 votos
1 respuesta
0 votos
0 respuestas
preguntado por rick_korn (120 puntos) Ene 28, 2016 en Java
Bienvenido a Dudas de Programación, donde puedes hacer preguntas y recibir respuestas sobre los problemas más frecuentes de los lenguajes de programación, frameworks de desarrollo y bases de datos que utilices. Foro de Línea de Código

Categorías

...