In Java, how I can get an open socket? I have 2 JFrames; in the first JFrame I open the connection of my Client socket. Inside this same JFrame I create an instance of another JFrame (JFrame2). Now I want to get the same Socket from JFrame1 into JFrame2 to continue talking with my server Socket:
try {
cliente = new Socket("localhost", 4444);
salida = new ObjectOutputStream(cliente.getOutputStream());
entrada = new ObjectInputStream(cliente.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: localhost.");
System.exit(1);
}
try {
while ((mensaje_entrada=(String)entrada.readObject()) != null) {
try {
me=td.encrypt(mensaje_entrada);
m2=td.decrypt(me);
} catch (Exception ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("e:"+ me);
System.out.println("de:"+ m2);
System.out.println(mensaje_entrada);
if(mensaje_entrada.equals("20")){
mensaje_salida=""+txt_usuario.getText()+","+txt_password.getText();
System.out.println(mensaje_salida);
salida.writeObject( mensaje_salida );
salida.flush();
mensaje_entrada=(String)entrada.readObject();
System.out.println(mensaje_entrada);
if(mensaje_entrada.equals("1")){
m.setLocationRelativeTo(null); <---- **m is another JFrame(Jframe2)**
m.setVisible(true);
//JOptionPane.showMessageDialog(this,"Funciona!!");
break;
}else if(mensaje_entrada.equals("2")){
JOptionPane.showMessageDialog(this,"Usuario o contraseña incorrecta!","Error!",JOptionPane.ERROR_MESSAGE);
break;
}
}
}
} catch (EOFException ex) { //This exception will be caught when EOF is reached
System.out.println("End of file reached.");
} catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(this,ex.getMessage());
} catch (IOException ex) {
JOptionPane.showMessageDialog(this,ex.getMessage());
}
Please take a look at the implementation of Singleton
With this you can access your object in an elegant way from everywhere and warranties that it will be uniquely instantiated.
A simple implementation following the approach of singleton for it:
package foo.bar;
import java.io.IOException;
import java.net.Socket;
public final class MySingletonSocket extends Socket {
private static Socket clientSocket;
static {
try {
clientSocket = new MySingletonSocket("localhost", 4444);
} catch (Exception e) {
e.printStackTrace();
}
}
private MySingletonSocket(final String address, final int port) throws IOException {
super(address, port);
}
public static final Socket getInstance() {
return clientSocket;
}
}
From JFrame1 you can access it like:
MySingletonSocket.getInstance()
From JFrame2 you can access it in the same way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With