java中套接字,如何在java中获得一个开放的套接字?
在
Java中,我如何獲得一個開放的套接字?我有2個JFrame;在第一個JFrame中,我打開了Client socket的連接.在同一個JFrame中,我創建了另一個JFrame(JFrame2)的實例.現在我想從JFrame1獲取相同的Socket到JFrame2繼續與我的服務器Socket交談:
login.java(First JFrame)
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);
}
login.java(第一個Jframe)
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.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());
}
最佳答案 請看一下
Singleton的實現
有了它,您可以從任何地方以優雅的方式訪問您的對象,并保證它將被唯一地實例化.
遵循單例方法的簡單實現:
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;
}
}
從JFrame1您可以訪問它,如:
MySingletonSocket.getInstance()
從JFrame2,您可以以相同的方式訪問它.
總結
以上是生活随笔為你收集整理的java中套接字,如何在java中获得一个开放的套接字?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab在电磁场与电磁波中的应用,m
- 下一篇: oracle账户解锁28000,orac