Java - desconexion del servidor soket

 
Vista:

desconexion del servidor soket

Publicado por Pau (1 intervención) el 24/02/2022 16:33:54
Buenas tengo un problema, me piden esto:
Actualmente, nuestro chat, si un usuario cierra la aplicación y otro le envía un mensaje, el servidor después de intentar realizar la conexión lanza una excepción y deja de escuchar peticiones. Debe solucionar este problema. Lo que le pido, es que localice dónde está el problema, y ​​lo gestione de la siguiente manera:

el codigo es el siguiente:
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
 
public class Cliente {
    public static void main(String[] args) {
        MarcoCliente mimarco = new MarcoCliente();
        mimarco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
 
class MarcoCliente extends JFrame {
    public MarcoCliente() {
        setBounds(600,300,280,350);
        LaminaMarcoCliente milamina = new LaminaMarcoCliente();
        add(milamina);
        setVisible(true);
 
        addWindowListener(new EnvioOnline());
    }
}
 
//-------------------------------------- ENVIO SEÑAL ONLINE -------------------------------------------------
class EnvioOnline extends WindowAdapter{
 
    public void windowOpened(WindowEvent e){
 
        try{
 
            Socket misocket = new Socket("172.16.251.207",9999);
            PaqueteEnvio datos = new PaqueteEnvio();
            datos.setMensaje(" online");
 
            ObjectOutputStream paquete_datos = new ObjectOutputStream(misocket.getOutputStream());
            paquete_datos.writeObject(datos);
 
            misocket.close();
 
        }catch (Exception e2){
        }
    }
}
//--------------------------------------------------------------------------------------------------------
 
class LaminaMarcoCliente extends JPanel implements Runnable{
 
    private JTextField campo1;
    private JComboBox ip;
    private JLabel nick;
    private JButton miboton;
    private JTextArea campochat;
 
 
    public LaminaMarcoCliente() {
 
        String nick_usuario=JOptionPane.showInputDialog("Nick_Name: ");
 
        JLabel n_nick= new JLabel("Nick_Name: ");
        add(n_nick);
 
        nick = new JLabel();
        nick.setText(nick_usuario);
        add(nick);
 
        JLabel texto = new JLabel("Online: ");
        add(texto);
 
        ip = new JComboBox();
 
        add(ip);
 
        campochat = new JTextArea(12,20);
        add(campochat);
 
        campo1 = new JTextField(20);
        add(campo1);
 
        miboton = new JButton("Enviar");
        EnviaTexto mievento = new EnviaTexto();
        miboton.addActionListener(mievento);
        add(miboton);
 
        Thread mihilo = new Thread(this);
        mihilo.start();
    }
 
    @Override
    public void run() {
 
        try{
 
            ServerSocket servidor_cliente = new ServerSocket(9090);
            Socket cliente;
 
            PaqueteEnvio paqueteRecibido;
 
            while(true){
                cliente=servidor_cliente.accept();
 
                ObjectInputStream flujoentrada = new ObjectInputStream(cliente.getInputStream());
                paqueteRecibido= (PaqueteEnvio) flujoentrada.readObject();
 
                if(!paqueteRecibido.getMensaje().equals(" online")){
                    campochat.append("\n" + paqueteRecibido.getNick() + ": " + paqueteRecibido.getMensaje());
                }else {
                    ArrayList<String> IpsMenu = new ArrayList<String>();
                    IpsMenu=paqueteRecibido.getIps();
 
                    ip.removeAllItems();
 
                    for(String z:IpsMenu){
                        ip.addItem(z);
                    }
                }
            }
 
        }catch (Exception e){
        System.out.println(e.getMessage());
        }
 
    }
 
    private class EnviaTexto implements ActionListener{
 
        @Override
        public void actionPerformed(ActionEvent e) {
 
            campochat.append("\n"+ campo1.getText());
 
            try {
                Socket misocket = new Socket("172.16.251.207",9999);
 
                PaqueteEnvio datos = new PaqueteEnvio();
                datos.setNick(nick.getText());
                datos.setIp(ip.getSelectedItem().toString());
                datos.setMensaje(campo1.getText());
 
                ObjectOutputStream paquete_datos = new ObjectOutputStream(misocket.getOutputStream());
                paquete_datos.writeObject(datos);
 
                misocket.close();
 
            } catch (IOException ex) {
                System.out.println(ex.getMessage());
            }
 
        }
    }
 
}
 
class PaqueteEnvio implements Serializable{
    private String nick, ip, mensaje;
 
    private ArrayList<String> Ips;
 
    public ArrayList<String> getIps() {
        return Ips;
    }
 
    public void setIps(ArrayList<String> ips) {
        Ips = ips;
    }
 
    public String getNick() {
        return nick;
    }
 
    public void setNick(String nick) {
        this.nick = nick;
    }
 
    public String getIp() {
        return ip;
    }
 
    public void setIp(String ip) {
        this.ip = ip;
    }
 
    public String getMensaje() {
        return mensaje;
    }
 
    public void setMensaje(String mensaje) {
        this.mensaje = mensaje;
    }
}

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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
 
public class Servidor {
    public static void main(String[] args) {
        MarcoServidor mimarco = new MarcoServidor();
        mimarco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
 
class MarcoServidor extends JFrame implements Runnable{
 
    private JTextArea areatexto;
 
    public MarcoServidor() {
        setBounds(1200,300,280,350);
        JPanel milamina = new JPanel();
        milamina.setLayout(new BorderLayout());
        areatexto = new JTextArea();
        milamina.add(areatexto, BorderLayout.CENTER);
        add(milamina);
        setVisible(true);
 
        Thread mihilo = new Thread(this);
        mihilo.start();
    }
 
 
 
    @Override
    public void run() {
        try {
            ServerSocket servidor = new ServerSocket(9999);
            String nick,ip,mensaje;
            ArrayList <String> listaIp = new ArrayList<String>();
            PaqueteEnvio paquete_recibido;
 
            while(true) {
 
                Socket misocket = servidor.accept();
 
 
                ObjectInputStream paquete_datos = new ObjectInputStream(misocket.getInputStream());
                paquete_recibido = (PaqueteEnvio) paquete_datos.readObject();
 
                nick = paquete_recibido.getNick();
                ip = paquete_recibido.getIp();
                mensaje = paquete_recibido.getMensaje();
 
 
                if(!mensaje.equals(" online")) {
 
                    areatexto.append("\n" + nick + ": " + mensaje + " para " + ip);
 
                    Socket enviaDestinatario = new Socket(ip, 9090);
                    ObjectOutputStream paqueteReenvio = new ObjectOutputStream(enviaDestinatario.getOutputStream());
                    paqueteReenvio.writeObject(paquete_recibido);
 
                    paqueteReenvio.close();
 
                    enviaDestinatario.close();
 
                    misocket.close();
                }else {
                    //------------------------------DETECTA ONLINE-----------------------------------
                    InetAddress localizacion=misocket.getInetAddress();
 
                    String IpRemota=localizacion.getHostAddress();
                    System.out.println("Online " + IpRemota);
 
                    listaIp.add(IpRemota);
 
                    paquete_recibido.setIps(listaIp);
 
                    for (String z:listaIp){
                        System.out.println("Array: " + z);
 
                        Socket enviaDestinatario = new Socket(z, 9090);
                        ObjectOutputStream paqueteReenvio = new ObjectOutputStream(enviaDestinatario.getOutputStream());
                        paqueteReenvio.writeObject(paquete_recibido);
 
                        paqueteReenvio.close();
 
                        enviaDestinatario.close();
 
                        misocket.close();
                    }
                    //-------------------------------------------------------------------------------
                }
            }
 
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
 
    }
}





GRAXIAS
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
sin imagen de perfil
Val: 755
Bronce
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

desconexion del servidor soket

Publicado por Yamil Bracho (2315 intervenciones) el 24/02/2022 16:48:11
El problema es que el tratamiento de IOException esta fuera del ciclo del server y por eso el server deja de responder porque te sales del loop de tratamiento de peticiones.
Creo que el problema es en rla apertura del canal del cliente o en el readObject del mismo asi quesas dos lineas encierralas en un try catch y cjequa en los javadco que excepcion arrojan para tene run control mas afinado de cual es la excepcion que debe hacer que el servidor termine o que ignore lapeticion sin salir
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar