简体   繁体   English

如何在java中获得一个打开的套接字?

[英]How to get an open socket in java?

In Java, how I can get an open socket?在 Java 中,如何获得打开的套接字? I have 2 JFrames;我有 2 个 JFrame; in the first JFrame I open the connection of my Client socket.在第一个 JFrame 中,我打开了客户端套接字的连接。 Inside this same JFrame I create an instance of another JFrame (JFrame2).在同一个 JFrame 中,我创建了另一个 JFrame (JFrame2) 的实例。 Now I want to get the same Socket from JFrame1 into JFrame2 to continue talking with my server Socket:现在我想从 JFrame1 获取相同的 Socket 到 JFrame2 以继续与我的服务器 Socket 通信:

login.java (First JFrame) login.java (第一个 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 (First Jframe) 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 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请看一下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:从 JFrame1 您可以像这样访问它:

MySingletonSocket.getInstance()

From JFrame2 you can access it in the same way.从 JFrame2,您可以以相同的方式访问它。

The best thing you can do is only do things that have to do with displaying things in your JFrame.您能做的最好的事情就是只做与在 JFrame 中显示内容有关的事情。

A JFrame shouldn't have a socket in it. JFrame 中不应该有套接字。 I know it CAN, but it shouldn't.我知道可以,但不应该。 You should have a class outside of your JFrame for business logic.您应该在 JFrame 之外有一个用于业务逻辑的类。 Then your controller object can spawn both your JFrames and your sockets.然后你的控制器对象可以产生你的 JFrames 和你的套接字。

Think of it like this: imagine instead of usign a JFrame you were writing your application for the command line.可以这样想:想象一下,您正在为命令行编写应用程序,而不是使用 JFrame。 Then, when you make your JFrames, have them issue commands to that command line application.然后,当您制作 JFrame 时,让它们向该命令行应用程序发出命令。 You'll find issues like this simply go away when you write your program with good layering.当您编写具有良好分层的程序时,您会发现这样的问题会消失。

Make that client Socket static.使该client Socket static.

eg:例如:

 static Socket client = new Socket;

As static member is for the class, and all objects share the same static variable, so the 2nd frame will have the same client socket.由于静态成员用于类,并且所有对象共享相同的静态变量,因此第二帧将具有相同的客户端套接字。

Another thing you can do is to pass the object reference of the client socket to the 2nd frame.您可以做的另一件事是将客户端套接字的对象引用传递到第二帧。

You can share the reference to the Client socket inside both JFrames.您可以在两个 JFrame 中共享对客户端套接字的引用。

This is possible through one of these two methods:这可以通过以下两种方法之一实现:

  1. Declare the socket as a static variable which can be accessed by both JFrame1 and JFrame2.将套接字声明为 JFrame1 和 JFrame2 都可以访问的静态变量。
  2. Pass the reference of the Socket into JFrame2将 Socket 的引用传递到 JFrame2

Inside JFrame2, have a method like this:在 JFrame2 中,有一个这样的方法:

public void setSocket(Socket s) {
    this.socket = s;
}

Then, call this method from JFrame1, and pass the socket in.然后,从 JFrame1 中调用此方法,并将套接字传入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM