elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Como proteger una cartera - billetera de Bitcoin


  Mostrar Temas
Páginas: [1]
1  Programación / Java / Chat multi-cliente en: 25 Febrero 2014, 06:50 am
Antes que nada saludos y gracias de antemano.

Tengo un problema al hacer un chat multi-cliente, cuando ejecuto el servidor y un cliente de la aplicacion todo funciona perfecto el problema viene cuando ejecuto el segundo cliente y envio un mensaje por el chat. Al enviar un mensaje desde el segundo cliente el JTextArea que es donde estan las conversaciones se agrega el mensaje dos veces y el JTextArea del primer cliente no se actualiza y deja de poner enviar mensajes.

Aqui les subire las clases de donde creo que ocurre el problema.


Código
  1. package com.gestion.garage.servidor;
  2.  
  3. import java.io.DataInputStream;
  4. import java.io.DataOutputStream;
  5. import java.io.IOException;
  6. import java.net.Socket;
  7.  
  8. import javax.swing.DefaultListModel;
  9. import javax.swing.event.ListDataEvent;
  10. import javax.swing.event.ListDataListener;
  11.  
  12. public class HiloDeCliente implements Runnable,ListDataListener{
  13. private DefaultListModel<String> conversacion;
  14. private static DataOutputStream dataSalida;
  15. private static DataInputStream dataEntrada;
  16. private Socket socket;
  17.  
  18. public HiloDeCliente(DefaultListModel<String> conversacion, Socket socket){
  19. this.conversacion = conversacion;
  20. this.socket = socket;
  21. try{
  22. dataSalida = new DataOutputStream(socket.getOutputStream());
  23. dataEntrada = new DataInputStream(socket.getInputStream());
  24. conversacion.addListDataListener(HiloDeCliente.this);
  25. }
  26. catch(Exception e){
  27. e.printStackTrace();
  28. }
  29. }
  30.  
  31. public static void cerrarFlujos() throws IOException{
  32. dataSalida.close();
  33. dataEntrada.close();
  34. }
  35. // No hace nada
  36. public void contentsChanged(ListDataEvent arg0) {}
  37.  
  38. public void intervalAdded(ListDataEvent e) {
  39. String texto = (String) conversacion.getElementAt(e.getIndex0());
  40. try{
  41. dataSalida.writeUTF(texto);
  42. }
  43. catch(Exception ex){
  44. ex.printStackTrace();
  45. }
  46. }
  47. //No hace nada
  48. public void intervalRemoved(ListDataEvent arg0) {
  49. }
  50.  
  51. public void run() {
  52. try{
  53. while(true){
  54. String texto = dataEntrada.readUTF();
  55. synchronized(conversacion){
  56. conversacion.addElement(texto);
  57. System.out.println("Hay "+conversacion.getSize()+" elementos");
  58. }
  59. }
  60. }catch(Exception e){
  61. e.printStackTrace();
  62.  
  63. }
  64. }
  65. }
  66.  
  67.  

Código
  1. package com.gestion.garage.InterfazGrafica;
  2.  
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import java.io.DataInputStream;
  6. import java.io.DataOutputStream;
  7. import java.net.Socket;
  8.  
  9. public class ControlCliente implements Runnable,ActionListener{
  10.  
  11. private DataOutputStream dataSalida;
  12. private DataInputStream dataEntrada;
  13. private VentanaAdministrador panel;
  14.  
  15. public ControlCliente(Socket socket,VentanaAdministrador panel){
  16. this.panel = panel;
  17. try{
  18. dataEntrada = new DataInputStream(socket.getInputStream());
  19. dataSalida = new DataOutputStream(socket.getOutputStream());
  20. panel.addActionListener(this);
  21. Thread hilo = new Thread(this);
  22. hilo.start();
  23. }
  24. catch(Exception ex){
  25. ex.printStackTrace();
  26. }
  27. }
  28.  
  29. public void actionPerformed(ActionEvent arg0) {
  30. try
  31.        {
  32.            dataSalida.writeUTF(panel.getTexto());
  33.        } catch (Exception excepcion)
  34.        {
  35.            excepcion.printStackTrace();
  36.        }
  37.  
  38. }
  39.  
  40. public void run() {
  41. try
  42.        {
  43.            while (true)
  44.            {
  45.                String texto = dataEntrada.readUTF();
  46.                panel.addTexto(texto);
  47.                panel.addTexto("\n");
  48.            }
  49.        } catch (Exception e)
  50.        {
  51.            e.printStackTrace();
  52.        }
  53. }
  54.  
  55. }
  56.  
  57.  

Código
  1. package com.gestion.garage.InterfazGrafica;
  2.  
  3. import java.awt.Font;
  4.  
  5. public class Login extends JFrame {
  6. private JTextField txtUsuario;
  7. private JPasswordField txtPassword;
  8. private Socket socket;
  9. private VentanaAdministrador panel;
  10. public Login(){
  11. setTitle("Login");
  12. setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
  13. setSize(354,308);
  14. getContentPane().setLayout(null);
  15.  
  16. addWindowListener(new WindowAdapter(){
  17. public void windowClosing(WindowEvent ev){
  18. int eleccion = JOptionPane.showConfirmDialog(null,"¿Desea cerrar esta ventana?");
  19. if(eleccion==0){
  20. try {
  21. HiloDeCliente.cerrarFlujos();
  22. System.exit(0);
  23. } catch (IOException e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. }
  28. });
  29. txtUsuario = new JTextField();
  30. txtUsuario.setBounds(98, 55, 143, 20);
  31. getContentPane().add(txtUsuario);
  32. txtUsuario.setColumns(10);
  33.  
  34. txtPassword = new JPasswordField();
  35. txtPassword.setBounds(98, 132, 143, 20);
  36. getContentPane().add(txtPassword);
  37.  
  38. JLabel lblUsuario = new JLabel("Usuario");
  39. lblUsuario.setFont(new Font("Cambria Math", Font.BOLD, 15));
  40. lblUsuario.setBounds(137, 27, 66, 14);
  41. getContentPane().add(lblUsuario);
  42.  
  43. JLabel lblPassword = new JLabel("Password");
  44. lblPassword.setFont(new Font("Cambria Math", Font.BOLD, 15));
  45. lblPassword.setBounds(131, 105, 82, 14);
  46. getContentPane().add(lblPassword);
  47.  
  48. JButton btnIniciar = new JButton("Iniciar");
  49. btnIniciar.addActionListener(new ActionListener() {
  50. public void actionPerformed(ActionEvent arg0) {
  51. System.out.println(ConexionMySql.getInstancia().verificarUsuario(txtUsuario.getText()));
  52. if(ConexionMySql.getInstancia().verificarUsuario(txtUsuario.getText())){
  53. try {
  54. new ControlCliente(new Socket("localhost",5557),new VentanaAdministrador(ConexionMySql.getInstancia().obtenerNombre(txtUsuario.getText())));
  55. } catch (IOException e) {
  56. e.printStackTrace();
  57. }
  58. Login.this.dispose();
  59. }
  60. else{
  61. JOptionPane.showMessageDialog(null, "No hay ningun usuario registrado con estos datos");
  62. }
  63. }
  64. });
  65. btnIniciar.setBounds(124, 181, 89, 23);
  66. getContentPane().add(btnIniciar);
  67.  
  68. JLabel lblRegistrarse = new JLabel("Registrarse");
  69. lblRegistrarse.addMouseListener(new MouseAdapter() {
  70.  
  71. public void mouseClicked(MouseEvent arg0) {
  72. new VentanaRegistro();
  73. Login.this.dispose();
  74. }
  75. });
  76. lblRegistrarse.setFont(new Font("Cambria Math", Font.BOLD, 15));
  77. lblRegistrarse.setBounds(225, 238, 89, 20);
  78. getContentPane().add(lblRegistrarse);
  79. setVisible(true);
  80. }
  81. }
  82.  
  83.  

Código
  1. package com.gestion.garage.servidor;
  2.  
  3. import java.net.ServerSocket;
  4. import java.net.Socket;
  5.  
  6. import javax.swing.DefaultListModel;
  7.  
  8. public class ServidorChat {
  9.  
  10. private DefaultListModel<String> conversacion = new DefaultListModel<String>();
  11. public static void main(String[] args){
  12. new ServidorChat();
  13. }
  14.  
  15. public ServidorChat(){
  16. try{
  17. ServerSocket socketServidor = new ServerSocket(5557);
  18. while(true){
  19. Socket cliente = socketServidor.accept();
  20. Runnable nuevoCliente = new HiloDeCliente(conversacion,cliente);
  21. Thread hilo = new Thread(nuevoCliente);
  22. hilo.start();
  23. }
  24. }catch(Exception e){
  25. e.printStackTrace();
  26. }
  27. }
  28. }
  29.  

Código
  1. package com.gestion.garage.InterfazGrafica;
  2.  
  3. import java.awt.Font;
  4.  
  5. public class VentanaAdministrador extends JFrame{
  6. private DataOutputStream dataSalida;
  7. private DataInputStream dataEntrada;
  8. private Socket socket;
  9. private static final int precio = 0;
  10. private static JTextField txtMensaje;
  11. private JComboBox cbRuedas;
  12. private JComboBox cbTipoVehiculo;
  13. private JComboBox cbModelo;
  14. private JButton btnCalcular;
  15. private JLabel lblPrecio;
  16. private JTable tblVehiculos;
  17. private JTextField txtPlaca;
  18. private JTextField txtPropietario;
  19. private JTextField txtMarca;
  20. private JButton btnRegistrar;
  21. private JButton btnEnviar;
  22. private JTextArea txtChat;
  23.  
  24. public VentanaAdministrador(String nombreUsuario) throws IOException{
  25. super("Garage - El Gomerito - ");
  26. setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
  27. setSize(764,421);
  28. getContentPane().setLayout(null);
  29.  
  30. addWindowListener(new WindowAdapter(){
  31. public void windowClosing(WindowEvent ev){
  32. int eleccion = JOptionPane.showConfirmDialog(null,"¿Desea cerrar esta ventana?");
  33. if(eleccion==0){
  34. new Login();
  35. VentanaAdministrador.this.dispose();
  36. }
  37. }
  38. });
  39.  
  40. JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
  41. tabbedPane.setBounds(0, 0, 748, 394);
  42. getContentPane().add(tabbedPane);
  43.  
  44. JPanel pnAlta = new JPanel();
  45. tabbedPane.addTab("Registro", null, pnAlta, null);
  46. pnAlta.setLayout(null);
  47.  
  48. cbTipoVehiculo = new JComboBox();
  49. cbTipoVehiculo.addActionListener(new ActionListener() {
  50. public void actionPerformed(ActionEvent arg0) {
  51. if(cbTipoVehiculo.getSelectedIndex() == 0){
  52. cbRuedas.setModel(new DefaultComboBoxModel(new String[]{"1","2","3","4"}));
  53. cbModelo.setModel(new DefaultComboBoxModel(new String[]{"Carro","Jeepeta","Camioneta"}));
  54. }
  55. else{
  56. cbRuedas.setModel(new DefaultComboBoxModel(new String[]{"1","2"}));
  57. cbModelo.setModel(new DefaultComboBoxModel(new String[]{"Pasola","Jumbo","Motor"}));
  58. }
  59. }
  60. });
  61. cbTipoVehiculo.setModel(new DefaultComboBoxModel(new String[] {"Coche", "Moto"}));
  62. cbTipoVehiculo.setBounds(202, 11, 107, 20);
  63. pnAlta.add(cbTipoVehiculo);
  64.  
  65. JLabel lblTipoVehiculo = new JLabel("Tipo Vehiculo");
  66. lblTipoVehiculo.setFont(new Font("Tahoma", Font.BOLD, 16));
  67. lblTipoVehiculo.setBounds(10, 11, 122, 17);
  68. pnAlta.add(lblTipoVehiculo);
  69.  
  70. JLabel lblRuedas = new JLabel("Ruedas");
  71. lblRuedas.setFont(new Font("Tahoma", Font.BOLD, 16));
  72. lblRuedas.setBounds(10, 60, 122, 14);
  73. pnAlta.add(lblRuedas);
  74.  
  75. cbRuedas= new JComboBox();
  76. cbRuedas.setBounds(202, 57, 107, 20);
  77. pnAlta.add(cbRuedas);
  78.  
  79. cbModelo = new JComboBox();
  80. cbModelo.setBounds(202, 107, 107, 20);
  81. pnAlta.add(cbModelo);
  82.  
  83. JLabel lblModelo = new JLabel("Modelo");
  84. lblModelo.setFont(new Font("Tahoma", Font.BOLD, 16));
  85. lblModelo.setBounds(10, 107, 122, 20);
  86. pnAlta.add(lblModelo);
  87.  
  88. lblPrecio = new JLabel("0.00");
  89. lblPrecio.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 32));
  90. lblPrecio.setBounds(202, 297, 92, 29);
  91. pnAlta.add(lblPrecio);
  92. btnRegistrar = new JButton("Registrar");
  93. btnRegistrar.setEnabled(false);
  94. btnRegistrar.addActionListener(new ActionListener() {
  95. public void actionPerformed(ActionEvent arg0) {
  96. if(txtMarca.getText().equals("") || txtPropietario.getText().equals("") || txtPlaca.getText().equals("")){
  97. JOptionPane.showMessageDialog(null,"Debe llenar todos los campos antes de registrar");
  98. }
  99. else{
  100. ModeloTabla.getInstancia().agregarVehiculo(new Vehiculo(txtMarca.getText(),txtPropietario.getText(),
  101. Integer.parseInt((String)cbRuedas.getSelectedItem()),txtPlaca.getText()));
  102. txtPropietario.setText("");
  103. txtMarca.setText("");
  104. txtPlaca.setText("");
  105. }
  106. }
  107. });
  108. btnRegistrar.setFont(new Font("Tahoma", Font.BOLD, 13));
  109. btnRegistrar.setBounds(538, 305, 107, 29);
  110. pnAlta.add(btnRegistrar);
  111.  
  112. btnCalcular = new JButton("Calcular");
  113. btnCalcular.setFont(new Font("Tahoma", Font.BOLD, 13));
  114. btnCalcular.addActionListener(new ActionListener() {
  115. public void actionPerformed(ActionEvent e) {
  116. if(cbTipoVehiculo.getSelectedIndex()==0 && cbRuedas.getSelectedIndex()==-1 && cbModelo.getSelectedIndex()==-1){
  117. JOptionPane.showMessageDialog(null, "Debe seleccionar el tipo de vehiculo");
  118. }
  119. else{
  120. btnRegistrar.setEnabled(true);
  121. if(cbTipoVehiculo.getSelectedItem().equals("Coche")){
  122. lblPrecio.setText(String.valueOf(400*Integer.parseInt((String)cbRuedas.getSelectedItem()))+"$");
  123. }
  124. else{
  125. lblPrecio.setText(String.valueOf(400*Integer.parseInt((String)cbRuedas.getSelectedItem()))+"$");
  126. }
  127. }
  128. }
  129. });
  130. btnCalcular.setBounds(38, 309, 89, 23);
  131. pnAlta.add(btnCalcular);
  132.  
  133. txtPlaca = new JTextField();
  134. txtPlaca.setBounds(202, 147, 107, 20);
  135. pnAlta.add(txtPlaca);
  136. txtPlaca.setColumns(10);
  137.  
  138. txtPropietario = new JTextField();
  139. txtPropietario.setBounds(202, 199, 107, 20);
  140. pnAlta.add(txtPropietario);
  141. txtPropietario.setColumns(10);
  142.  
  143. JLabel lblPlaca = new JLabel("Placa");
  144. lblPlaca.setFont(new Font("Tahoma", Font.BOLD, 16));
  145. lblPlaca.setBounds(10, 153, 122, 14);
  146. pnAlta.add(lblPlaca);
  147.  
  148. JLabel lblPropietario = new JLabel("Propietario");
  149. lblPropietario.setFont(new Font("Tahoma", Font.BOLD, 16));
  150. lblPropietario.setBounds(10, 200, 122, 14);
  151. pnAlta.add(lblPropietario);
  152.  
  153. JLabel lblMarca = new JLabel("Marca");
  154. lblMarca.setFont(new Font("Tahoma", Font.BOLD, 16));
  155. lblMarca.setBounds(10, 251, 122, 14);
  156. pnAlta.add(lblMarca);
  157.  
  158. txtMarca = new JTextField();
  159. txtMarca.setBounds(202, 246, 107, 20);
  160. pnAlta.add(txtMarca);
  161. txtMarca.setColumns(10);
  162.  
  163. JLabel lblBienvenido = new JLabel("Bienvenido: ");
  164. lblBienvenido.setFont(new Font("Tahoma", Font.BOLD, 16));
  165. lblBienvenido.setBounds(378, 14, 116, 17);
  166. pnAlta.add(lblBienvenido);
  167.  
  168. JLabel lblNombreUsuario = new JLabel(nombreUsuario);
  169. lblNombreUsuario.setFont(new Font("Tahoma", Font.BOLD, 16));
  170. lblNombreUsuario.setBounds(504, 11, 212, 20);
  171. pnAlta.add(lblNombreUsuario);
  172.  
  173. JPanel pnChat = new JPanel();
  174. tabbedPane.addTab("Chat", null, pnChat, null);
  175. pnChat.setLayout(null);
  176.  
  177. JScrollPane scrollPane = new JScrollPane();
  178. scrollPane.setBounds(0, 0, 733, 294);
  179. pnChat.add(scrollPane);
  180.  
  181. txtChat = new JTextArea();
  182. scrollPane.setViewportView(txtChat);
  183. txtChat.setEditable(false);
  184.  
  185. txtMensaje = new JTextField();
  186. txtMensaje.setBounds(0, 298, 610, 27);
  187. pnChat.add(txtMensaje);
  188. txtMensaje.setColumns(10);
  189.  
  190. btnEnviar = new JButton("Enviar");
  191. btnEnviar.setBounds(611, 298, 120, 27);
  192. pnChat.add(btnEnviar);
  193. JPanel pnGarage = new JPanel();
  194. tabbedPane.addTab("Garage", null, pnGarage, null);
  195. pnGarage.setLayout(null);
  196.  
  197. JButton btnDespachar = new JButton("Despachar");
  198. btnDespachar.addActionListener(new ActionListener() {
  199. public void actionPerformed(ActionEvent arg0) {
  200. if(tblVehiculos.getSelectedRow()==-1){
  201. JOptionPane.showMessageDialog(null, "Debe seleccionar una columna");
  202. }
  203. else{
  204. ModeloTabla.getInstancia().borrarVehiculo(tblVehiculos.getSelectedRow());
  205. }
  206. }
  207. });
  208. btnDespachar.setFont(new Font("Tahoma", Font.BOLD, 16));
  209. btnDespachar.setBounds(273, 309, 132, 29);
  210. pnGarage.add(btnDespachar);
  211.  
  212. JScrollPane scrollPane_1 = new JScrollPane();
  213. scrollPane_1.setBounds(10, 29, 708, 212);
  214. pnGarage.add(scrollPane_1);
  215.  
  216. tblVehiculos = new JTable();
  217. tblVehiculos.setModel(ModeloTabla.getInstancia());
  218. scrollPane_1.setViewportView(tblVehiculos);
  219. setVisible(true);
  220. }
  221. public void addActionListener(ActionListener accion){
  222. txtMensaje.addActionListener(accion);
  223. btnEnviar.addActionListener(accion);
  224. }
  225.  
  226. public  void addTexto(String texto){
  227. txtChat.append(texto);
  228. }
  229.  
  230. public String getTexto(){
  231. String texto = txtMensaje.getText();
  232. txtMensaje.setText("");
  233. return texto;
  234. }
  235.  
  236. }
  237.  

Código
  1. package com.gestion.garage.practicas;
  2.  
  3. import com.gestion.garage.InterfazGrafica.Login;
  4.  
  5. public class SistemaGarage {
  6. public static void main(String[] args){
  7. new Login();
  8. }
  9. }

Cualquier duda acerca del codigo me avisan, espero sus respuestas :)
Páginas: [1]
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines