Java - Ayuda de código sobre socket e hilos.

 
Vista:

Ayuda de código sobre socket e hilos.

Publicado por Ivan (1 intervención) el 27/10/2019 19:37:17
Buenas a todos,
la verdad que no se como resolver esto que me esta pasando. Y es que cuando corro el servidor y el clientes hasta ahi todo bien, el problema es cuando quiero enviar algun mensaje y no me responde el mensaje. No lo percibe el servidor y por lo tanto el mensaje no sale.

Alguien podría echarme una mano?

Os pongo el código abajo.

Gracias a todos de ante mano .

SERVIDOR

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package chat;
 
import java.io.DataInputStream;
 
import java.net.ServerSocket;
 
import java.net.Socket;
 
import javax.swing.JOptionPane;
 
 
public class Servidor extends javax.swing.JFrame {
 
    private ServerSocket server;
 
    private final int PUERTOH=2222;
 
 
 
    public Servidor() {
        initComponents();
 
        try{
            server = new ServerSocket (PUERTOH);
            mensajeria (" Servidor Online \n");
 
            super.setVisible(true);
 
            while(true){
 
                Socket cliente = server.accept();
                mensajeria("Cliente conectado desde" + cliente.getInetAddress().getHostAddress());
 
                DataInputStream entrada = new DataInputStream(cliente.getInputStream());
 
                HiloServidor hilo = new HiloServidor (cliente,entrada.readUTF(),this);
                hilo.start();
 
 
            }
        } catch (Exception e){
            JOptionPane.showMessageDialog(this, e.toString());
        }
    }
 
    public void mensajeria( String msg){
        this.jTextArea1.append(" "+msg+"\n");
    }
 
 
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
 
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
 
        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 431, Short.MAX_VALUE)
        );
 
        pack();
    }// </editor-fold>                        
 
 
    public static void main(String args[]) {
 
      new Servidor();
 
     }
 
 
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
}

HILO SERVIDOR

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class HiloServidor extends Thread {
 
    private DataInputStream entrada;
    private DataOutputStream salida;
    private Servidor server;
    private Socket Cliente;
    public static Vector<HiloServidor> usuarioActivo = new Vector ();
    private String nombre;
    private ObjectOutputStream salidaObjeto;
 
    public HiloServidor (Socket socketcliente, String nombre, Servidor serv) throws Exception {
 
        this.Cliente = socketcliente;
        this.server = serv;
        this.nombre = nombre;
        usuarioActivo.add(this);
 
        for (int i=0 ; i < usuarioActivo.size(); i++){
            usuarioActivo.get(i).enviosMensajes(nombre+ " se conecto ");
 
 
        }
    }
    public void run (){
        String mensaje = " ";
        while(true){
            try{
                entrada= new DataInputStream(Cliente.getInputStream());
                mensaje = entrada.readUTF();
 
                for(int i = 0; i < usuarioActivo.size(); i++) {
 
                    usuarioActivo.get(i).enviosMensajes(mensaje);
                    server.mensajeria("Mensaje enviado");
                }
 
            } catch(Exception e) {
                break;
            }
        }
        usuarioActivo.removeElement(this);
        server.mensajeria("El usuario se desconecto");
 
        try{
            Cliente.close();
 
        } catch (Exception e){
 
        }
    }
 
    private void enviosMensajes (String msg) throws Exception {
        salida = new DataOutputStream(Cliente.getOutputStream());
        salida.writeUTF(msg);
        DefaultListModel modelo = new DefaultListModel();
 
        for (int i = 0; i < usuarioActivo.size(); i++) {
            modelo.addElement(usuarioActivo.get(i).nombre);
 
        }
 
        salidaObjeto = new ObjectOutputStream(Cliente.getOutputStream());
        salidaObjeto.writeObject(modelo);
 
    }
 
}

CLIENTE

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package chat;
 
import java.io.DataOutputStream;
import java.io.DataInputStream;
import java.io.InputStream;
import java.net.Socket;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
 
 
public class Cliente extends javax.swing.JFrame {
 
        private Socket cliente;
        private final int PUERTOC = 2222;
        private String host = "localhost";
        private DataOutputStream salida;
        private String nombre;
 
 
    public Cliente() {
        initComponents();
 
        try{
            nombre = JOptionPane.showInputDialog(" Indica tu nombre ");
            super.setTitle(super.getTitle()+ nombre);
            super.setVisible(true);
            cliente = new Socket(host, PUERTOC);
            DataOutputStream salida = new DataOutputStream(cliente.getOutputStream());
            salida.writeUTF(nombre);
            HiloCliente hilo = new HiloCliente(cliente, this);
            hilo.start();
 
 
        } catch (Exception e){
            JOptionPane.showMessageDialog(this, e.toString());
 
        }
    }
          public void mensajeria (String msg) {
            this.jTextArea1.append(" " + msg + "\n");
        }
 
 
    @SuppressWarnings("unchecked")
 
 
    private void SalidaEvento(java.awt.event.ActionEvent evt) {
        try{
            salida = new DataOutputStream(cliente.getOutputStream());
            salida.writeUTF(nombre+" : "+this.jTextField1.getText());
            this.jTextField1.setText(" ");
        } catch (Exception e){
 
        }
    }
 
    public void actualizarLista(DefaultListModel modelo){
 
        this.jList2.setModel(modelo);
 
    }
    public static void main(String args[]) {
 
        new Cliente();
 
    }
 
    private javax.swing.JButton jButton1;
    private javax.swing.JList<String> jList2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSplitPane jSplitPane2;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
}

HILO CLIENTE


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package chat;
 
import java.io.DataInputStream;
 
import java.io.IOException;
 
import java.io.ObjectInputStream;
 
import java.net.Socket;
 
import java.util.logging.Level;
 
import java.util.logging.Logger;
 
import javax.swing.DefaultListModel;
 
 
 
 
public class HiloCliente extends Thread {
 
    private Socket SocketCliente;
    private DataInputStream entrada;
    private Cliente cliente;
    private ObjectInputStream entradaObjeto;
 
    public HiloCliente(Socket SocketCliente, Cliente cliente){
        this.SocketCliente = SocketCliente;
        this.cliente = cliente;
 
    }
 
    public void run(){
        while(true) {
            try{
                entrada = new DataInputStream(SocketCliente.getInputStream());
                cliente.mensajeria(entrada.readUTF());
 
                entradaObjeto = new ObjectInputStream(SocketCliente.getInputStream());
                cliente.actualizarLista((DefaultListModel)entradaObjeto.readObject());
 
            }catch (ClassNotFoundException ex){
                Logger.getLogger(HiloCliente.class.getName()).log(Level.SEVERE, null, ex);
            }catch (IOException ex){
                Logger.getLogger(HiloCliente.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
 
 
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder