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

 

 


Tema destacado: Estamos en la red social de Mastodon


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  JavaFX, conexión por socket
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: JavaFX, conexión por socket  (Leído 2,060 veces)
Zoik

Desconectado Desconectado

Mensajes: 91


Ver Perfil
JavaFX, conexión por socket
« en: 25 Junio 2015, 13:05 pm »

Buenas a todos gente.

Tengo una preguntilla respecto a este tema, como podria hacer para tener una gui y que a la hora de conectar con el servidor no se me congelase la interface, pongo el código hasdta ahora:

Código
  1. package app;
  2.  
  3. import java.io.IOException;
  4.  
  5. import app.view.NewServerController;
  6. import app.view.RootController;
  7. import javafx.application.Application;
  8. import javafx.fxml.FXMLLoader;
  9. import javafx.scene.Scene;
  10. import javafx.scene.layout.BorderPane;
  11. import javafx.stage.Modality;
  12. import javafx.stage.Stage;
  13.  
  14.  
  15. public class Main extends Application
  16. {
  17.  
  18. private Stage stage;
  19. private BorderPane rootLayout;
  20.  
  21. public static void main(String[] args)
  22. {
  23. launch(args);
  24. }
  25.  
  26. @Override
  27. public void start(Stage stage) throws Exception
  28. {
  29. this.stage = stage;
  30. this.stage.setTitle("Fenrir");
  31.  
  32. initRootLayout();
  33. }
  34.  
  35. public void initRootLayout()
  36. {
  37. try
  38. {
  39. FXMLLoader loader = new FXMLLoader();
  40. loader.setLocation(Main.class.getResource("view/Root.fxml"));
  41. rootLayout = (BorderPane) loader.load();
  42.  
  43. RootController controller = loader.getController();
  44. controller.setMain(this);
  45.  
  46. Scene scene = new Scene(rootLayout);
  47. stage.setScene(scene);
  48. stage.show();
  49. } catch(IOException e)
  50. {
  51. e.printStackTrace();
  52. }
  53. }
  54.  
  55. public boolean showNewServerDialog()
  56. {
  57. try
  58. {
  59. FXMLLoader loader = new FXMLLoader();
  60. loader.setLocation(Main.class.getResource("view/NewServer.fxml"));
  61. BorderPane page = (BorderPane) loader.load();
  62.  
  63. Stage stage = new Stage();
  64. stage.setTitle("Conectar a servidor");
  65. stage.initModality(Modality.WINDOW_MODAL);
  66. stage.initOwner(this.stage);
  67. Scene scene = new Scene(page);
  68. stage.setResizable(false);
  69. stage.setScene(scene);
  70.  
  71. NewServerController controller = loader.getController();
  72. controller.setDialogStage(stage);
  73.  
  74. stage.showAndWait();
  75.  
  76. return controller.isOkCliked();
  77. } catch(IOException e)
  78. {
  79. e.printStackTrace();
  80. return false;
  81. }
  82. }
  83.  
  84. }
  85.  

Código
  1. package app.client;
  2.  
  3. import java.io.DataInputStream;
  4. import java.io.DataOutputStream;
  5. import java.net.Socket;
  6. import java.net.UnknownHostException;
  7.  
  8. public class Client
  9. {
  10.  
  11. private String hostname;
  12. private int puerto;
  13. Socket socket;
  14. DataInputStream entrada;
  15.  
  16. public Client(String hostname, int puerto)
  17. {
  18. this.hostname = hostname;
  19. this.puerto = puerto;
  20. }
  21.  
  22. public boolean InitClient()
  23. {
  24. try
  25. {
  26. socket = new Socket(hostname, puerto);
  27. entrada = new DataInputStream(socket.getInputStream());
  28. mensaje = new DataOutputStream(socket.getOutputStream());
  29. System.out.println(entrada.readUTF());
  30. mensaje.writeUTF("Hola que tal!");
  31. System.out.println(entrada.readUTF());
  32. socket.close();
  33. {
  34. e.printStackTrace();
  35. return false;
  36. } catch(Exception e)
  37. {
  38. e.printStackTrace();
  39. return false;
  40. }
  41. return true;
  42. }
  43.  
  44. }
  45.  

Código
  1. package app.view;
  2.  
  3. import org.controlsfx.dialog.Dialogs;
  4.  
  5. import app.client.Client;
  6. import javafx.fxml.FXML;
  7. import javafx.scene.control.TextField;
  8. import javafx.stage.Stage;
  9.  
  10. public class NewServerController
  11. {
  12. @FXML
  13. private TextField hostnameIpTextField;
  14. @FXML
  15. private TextField puertoTextField;
  16. @FXML
  17. private TextField userTextField;
  18. @FXML
  19. private TextField passwordTextField;
  20. @FXML
  21. private TextField nameTextField;
  22.  
  23. private Stage stage;
  24. private boolean okClicked = false;
  25.  
  26. public void setDialogStage(Stage stage)
  27. {
  28. this.stage = stage;
  29. }
  30.  
  31. public boolean isOkCliked()
  32. {
  33. return okClicked;
  34. }
  35.  
  36. private boolean isInputValid()
  37. {
  38. String errorMessage = "";
  39.  
  40. if(hostnameIpTextField.getText() == null
  41. || hostnameIpTextField.getText().length() == 0)
  42. errorMessage += "Hostname/Ip no válido!\n";
  43. if(puertoTextField.getText() == null
  44. || puertoTextField.getText().length() == 0
  45. || Integer.parseInt(puertoTextField.getText()) < 0
  46. || Integer.parseInt(puertoTextField.getText()) > 65535)
  47. errorMessage += "Puerto no válido!\n";
  48. if(errorMessage.length() == 0)
  49. {
  50. return true;
  51. } else
  52. {
  53. Dialogs.create()
  54.            .title("Campos inválidos")
  55.            .masthead("Por favor, corrige los campos no válidos")
  56.            .message(errorMessage)
  57.            .showError();
  58.        return false;
  59. }
  60. }
  61.  
  62. @FXML
  63. private void handleConectar() throws InterruptedException
  64. {
  65. if(isInputValid())
  66. {
  67. Client client = new Client(hostnameIpTextField.getText(), Integer.parseInt(puertoTextField.getText()));
  68. boolean connected = client.InitClient();
  69. if(connected)
  70. {
  71. okClicked = true;
  72. stage.close();
  73. }
  74. }
  75. }
  76.  
  77. @FXML
  78. private void handleCancelar()
  79. {
  80. stage.close();
  81. }
  82.  
  83. }
  84.  

Código
  1. package app.view;
  2.  
  3. import javafx.fxml.FXML;
  4. import app.Main;
  5.  
  6. public class RootController
  7. {
  8.  
  9. private Main main;
  10.  
  11. public void setMain(Main main)
  12. {
  13. this.main = main;
  14. }
  15.  
  16. @FXML
  17. private void handleNewServer()
  18. {
  19. boolean okClicked = main.showNewServerDialog();
  20. }
  21.  
  22. }
  23.  

Imagino que se hará la ejecución de la conexión del socket en un thread a parte, pero no me acaba de quedar claro como haría la trata de errores en el thread.

La idea que tenia era que en cuanto le de a conectar, me abra el socket en un thread separado para que la interface no se congele y en cuanto se conecte correctamente  (o no) avise al thread principal para que actue en consecuencia.

Un saludo y gracias de antemano.


« Última modificación: 25 Junio 2015, 18:41 pm por Zoik » En línea

Zoik

Desconectado Desconectado

Mensajes: 91


Ver Perfil
Re: JavaFX, conexión por socket
« Respuesta #1 en: 25 Junio 2015, 18:54 pm »

Bueno, me respondo en otro post, no se si será el método mas correcto pero aquí lo dejo por si a alguien le interesa.

Código
  1. package app.view;
  2.  
  3. import org.controlsfx.dialog.Dialogs;
  4.  
  5. import app.client.Client;
  6. import javafx.fxml.FXML;
  7. import javafx.scene.control.TextField;
  8. import javafx.stage.Stage;
  9.  
  10. public class NewServerController
  11. {
  12. @FXML
  13. private TextField hostnameIpTextField;
  14. @FXML
  15. private TextField puertoTextField;
  16. @FXML
  17. private TextField userTextField;
  18. @FXML
  19. private TextField passwordTextField;
  20. @FXML
  21. private TextField nameTextField;
  22.  
  23. private Stage stage;
  24. private boolean okClicked = false;
  25.  
  26. public void setDialogStage(Stage stage)
  27. {
  28. this.stage = stage;
  29. }
  30.  
  31. public boolean isOkCliked()
  32. {
  33. return okClicked;
  34. }
  35.  
  36. private boolean isInputValid()
  37. {
  38. String errorMessage = "";
  39.  
  40. if(hostnameIpTextField.getText() == null
  41. || hostnameIpTextField.getText().length() == 0)
  42. errorMessage += "Hostname/Ip no válido!\n";
  43. if(puertoTextField.getText() == null
  44. || puertoTextField.getText().length() == 0
  45. || Integer.parseInt(puertoTextField.getText()) < 0
  46. || Integer.parseInt(puertoTextField.getText()) > 65535)
  47. errorMessage += "Puerto no válido!\n";
  48. if(errorMessage.length() == 0)
  49. {
  50. return true;
  51. } else
  52. {
  53. Dialogs.create()
  54.            .title("Campos inválidos")
  55.            .masthead("Por favor, corrige los campos no válidos")
  56.            .message(errorMessage)
  57.            .showError();
  58.        return false;
  59. }
  60. }
  61.  
  62. @FXML
  63. private void handleConectar() throws InterruptedException
  64. {
  65. if(isInputValid())
  66. {
  67. Client client = new Client(hostnameIpTextField.getText(), Integer.parseInt(puertoTextField.getText()));
  68. client.start();
  69. client.join();
  70. boolean ok = client.getOk();
  71. if(ok)
  72. {
  73. System.out.println("Conexion exitosa, cierro modal...");
  74. okClicked = true;
  75. stage.close();
  76. }  else
  77. {
  78. System.out.println("Conexion fallida...");
  79. }
  80.  
  81. }
  82. }
  83.  
  84. @FXML
  85. private void handleCancelar()
  86. {
  87. stage.close();
  88. }
  89.  
  90. }
  91.  

Código
  1. package app.client;
  2.  
  3. import java.io.DataInputStream;
  4. import java.io.DataOutputStream;
  5. import java.net.Socket;
  6. import java.net.UnknownHostException;
  7.  
  8. public class Client extends Thread
  9. {
  10.  
  11. private String hostname;
  12. private int puerto;
  13. private Socket socket;
  14. private DataOutputStream mensaje;
  15. private DataInputStream entrada;
  16. private boolean ok = false;
  17.  
  18. public Client(String hostname, int puerto)
  19. {
  20. this.hostname = hostname;
  21. this.puerto = puerto;
  22. }
  23.  
  24. public boolean getOk()
  25. {
  26. return ok;
  27. }
  28.  
  29. public boolean InitClient()
  30. {
  31. try
  32. {
  33. socket = new Socket(hostname, puerto);
  34. entrada = new DataInputStream(socket.getInputStream());
  35. mensaje = new DataOutputStream(socket.getOutputStream());
  36. System.out.println(entrada.readUTF());
  37. mensaje.writeUTF("Hola que tal!");
  38. System.out.println(entrada.readUTF());
  39. socket.close();
  40. {
  41. e.printStackTrace();
  42. return false;
  43. } catch(Exception e)
  44. {
  45. e.printStackTrace();
  46. return false;
  47. }
  48. return true;
  49. }
  50.  
  51. public synchronized void run()
  52. {
  53. System.out.println("Inicio Thread");
  54. ok = InitClient();
  55. System.out.println("Conexion finalizada, notifico a thread principal");
  56. notifyAll();
  57. System.out.println("Notificado a thread");
  58. }
  59.  
  60. }
  61.  

Me sigue congelando la screen, pero al menos me espera a tener la respuesta afirmativa del thread del socket.

Un saludo y agradecería me comentarais si hay alguna forma mejor.


« Última modificación: 25 Junio 2015, 19:57 pm por Zoik » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Deteccion perdida de conexion socket en C
Programación C/C++
PeKiN 4 5,649 Último mensaje 14 Junio 2011, 17:56 pm
por PeKiN
Probar conexión Socket?
Programación C/C++
CeroX901 3 6,591 Último mensaje 18 Octubre 2011, 21:46 pm
por CeroX901
Conexion a socket
Java
lomaximo 5 3,475 Último mensaje 28 Mayo 2012, 16:17 pm
por lomaximo
[JavaFX] Manual para aprender JavaFX
Java
jaxoR 1 10,568 Último mensaje 17 Noviembre 2013, 20:16 pm
por Mitsu
[JavaEE - JavaFx] RESTful con JPA (CRUD) y cliente en JavaFX
Java
Usuario Invitado 2 4,232 Último mensaje 10 Abril 2015, 22:43 pm
por Usuario Invitado
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines