Skip to main content
2 de 2
codigo en su tag respectivo
Diego Avila
  • 5.5k
  • 6
  • 21
  • 48

chat tcp java.enviar mensaje a todos los clientes

buenos dias estoy haciendo un chat donde el objetivo es enviar un mensaje de un cliente a un servidor y del servidor a todos los clientes. esta ultima parte es la que no logro hacer.es decir que reenvie el mensaje a todos los clientes.

les dejo el codigo y escucho consejos.

package Cliente;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.IOException;
import java.net.Socket;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

public class Cliente extends JFrame {

    private Socket socket;
    private PanelCliente panel;

    public Cliente(int puerto) {

        try {
            panel = new PanelCliente();

            socket = new Socket("localhost", puerto);

            Runnable cliente =  new HiloCliente(socket, panel);
            Thread hilo = new Thread(cliente);
            hilo.start();
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        Cliente frame = new Cliente(10000);

    }
}
------------------------------------------------------------------------

package Cliente;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JPanel;

public class HiloCliente implements Runnable {

    private DataInputStream entrada;
    private DataOutputStream salida;
    private PanelCliente panel;
    private Socket socket;
    
    public HiloCliente(Socket socket, PanelCliente panel) {
        this.socket= socket;
        this.panel = panel;
        try {
            entrada = new DataInputStream(this.socket.getInputStream());
            salida = new DataOutputStream(this.socket.getOutputStream());
    

            this.panel.getBtnEnviar().addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent arg0) {
                    try {
                        salida.writeUTF(panel.getTexto());
                        HiloCliente.this.panel.setTextField("");
                    } catch (IOException e) {
                        
                        e.printStackTrace();
                    }

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

    }

    @Override
    public void run() {

        while (true) {
            try {

                String texto = entrada.readUTF();
                System.out.println(texto);
                panel.agregarTexto(texto);
                panel.agregarTexto("\n");

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

    }

}
-----------------------------------------------------------------------------
package Cliente;

import java.io.Serializable;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

public class PanelCliente extends JFrame implements Serializable {
    private JPanel contentPane;
    private JTextField textField;
    private JTextArea textArea;
    private JButton btnEnviar;
    private JScrollPane scrollPane;
    
    public PanelCliente() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(null);
        setContentPane(contentPane);

        btnEnviar = new JButton("Enviar");
        btnEnviar.setBounds(171, 195, 89, 23);
        contentPane.add(btnEnviar);

        textArea = new JTextArea();
        

        scrollPane = new JScrollPane(textArea);
        scrollPane.setBounds(40, 11, 350, 151);
        contentPane.add(scrollPane);

        textField = new JTextField();
        textField.setBounds(32, 196, 86, 20);
        contentPane.add(textField);
        textField.setColumns(10);

        setVisible(true);
    }

    public void setTextField(String string) {
        this.textField.setText(string);
    }

    public String getTexto() {
        return textField.getText();
        
    }

    public JButton getBtnEnviar() {
        return btnEnviar;
    }
    
    public void agregarTexto(String texto) {
        textArea.append(texto);
    }

    
    
    
}
------------------------------------------------------------------------------
package Servidor;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;

public class Servidor {

    private ServerSocket serversocket;
    private int puerto;
    boolean corriendo = true;
    private PanelServidor panel;
    private static int idCliente;
    private LinkedList<HiloServidor> Clientes;

    public Servidor(int puerto) {

        Clientes = new LinkedList<HiloServidor>();
        this.puerto = puerto;
        panel = new PanelServidor();

        Socket conexion = null;

        try {

            serversocket = new ServerSocket(this.puerto);

            while (true) {
                conexion = serversocket.accept();
                //HiloServidor cliente = new HiloServidor(conexion, panel, ++idCliente);
                Runnable hiloNuevoCliente = new HiloServidor(conexion, panel, ++idCliente);
                Thread hilo = new Thread(hiloNuevoCliente);
                hilo.start();
                //Clientes.add(cliente);
            }
        } catch (IOException e) {
            e.printStackTrace();

        }

    }

    public static void main(String[] args) {

        Servidor server = new Servidor(10000);
    }
}
--------------------------------------------------------------------------
package Servidor;

import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.LinkedList;

import javax.swing.DefaultListModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

public class HiloServidor implements Runnable {

    private Socket socket;
    private PanelServidor panel;
    private DataInputStream entrada;
    private DataOutputStream salida;
    private int idCliente;
    private Socket socketReenvio;
    
    public HiloServidor(Socket socket, PanelServidor panel, int idCliente) {
        this.socket = socket;
        this.panel = panel;
        this.idCliente = idCliente;

        try {
            salida = new DataOutputStream(this.socket.getOutputStream());
            entrada = new DataInputStream(this.socket.getInputStream());
            

        } catch (IOException e) {

            e.printStackTrace();
        }

    }

    @Override
    public void run() {

        while (true) {
            try {
                String texto = entrada.readUTF();

                panel.getTextArea().append("cliente " + idCliente + ": " + texto);
                panel.getTextArea().append("\n");

                salida.writeUTF(texto);

            } catch (IOException e) {

                e.printStackTrace();
            }
        }

    }

}

------------------------------------------------------------------------------
package Servidor;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class PanelServidor extends JFrame {

    private JPanel contentPane;
    private JTextArea textArea;
    private JScrollPane scrollPane;

    public PanelServidor() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(null);
        setContentPane(contentPane);

        textArea = new JTextArea();

        scrollPane = new JScrollPane(textArea);
        scrollPane.setBounds(68, 41, 257, 142);
        contentPane.add(scrollPane);

        setVisible(true);

    }

    public JTextArea getTextArea() {
        return textArea;
    }

    
}