I have the following code, which describes that if a window opens, it should render a dialog visible, connect to the server, and receive data:
private void formWindowOpened(java.awt.event.WindowEvent evt) {
this.jDialog1.setVisible(true);
con = new Conexion();
SwingWorker work = new SwingWorker() {
@Override
public Object doInBackground() {
con.recibirDatos();
return null;
}
@Override
public void done() {
jDialog1.dispose();
jDialog2.setVisible(true);
}
};
work.execute();
}
Now, Conexion does the following, client-wise:
public Conexion() {
try
{
this.puerto = 7896;
this.s = new Socket("localhost", puerto);
this.entrada = new DataInputStream(s.getInputStream());
this.salida = new DataOutputStream(s.getOutputStream());
}
catch(UnknownHostException e){ System.out.println("Socket: "+e.getMessage()); }
catch(EOFException e){ System.out.println("EOF: "+e.getMessage()); }
catch(IOException e){ System.out.println("IO: "+e.getMessage()); }
}
public void recibirDatos() {
try
{
this.salida.writeUTF("sendData");
System.out.println("Leyendo...");
this.color = this.entrada.readUTF();
this.ancho = this.entrada.readInt();
System.out.println("Datos recibidos: "+color+" "+ancho);
}
catch(UnknownHostException e){ System.out.println("Socket: "+e.getMessage()); }
catch(EOFException e){ System.out.println("EOF: "+e.getMessage()); }
catch(IOException e){ System.out.println("IO: "+e.getMessage()); }
}
Server-wise, the following happens when a connection is read:
public void enviarDatos(String color, int anchoLinea) {
try
{
System.out.println(entradaCliente.readUTF()+"! Enviando datos: "+color+" "+anchoLinea);
salidaCliente.flush();
salidaCliente.writeUTF(color);
salidaCliente.writeInt(anchoLinea);
System.out.println("Datos enviados.");
}
catch(EOFException e){ System.out.println("EOF: "+e.getMessage()); }
catch(IOException e){ System.out.println("IO: "+e.getMessage()); }
}
The issue:
- When I execute this, the client gets stuck on
readUTF()although the server already sent the data. - If I only send and receive an integer, I get the value
-1393754107instead of the number I'm sending, however the client doesn't get stuck. - When I send data from the client to the server it works just fine.
What could be the problem? Thank you beforehand.
EDIT: I also found out that, if the server shuts down while the client is waiting due to readUTF(), the client gets an IOException, which means the client is actually connected to the server, but for some reason it's not reading data from it!