单例模式-服务器套接字



我使用这个代码:

    final int LOCK_PORT= 54321;
    ServerSocket ss = new ServerSocket(LOCK_PORT);

问题是,在同一个端口你不能听两个不同的应用程序(教师理论)。

这段代码被实现到一个应用程序中,同一个实例运行了不止一次。目标是同一个实例不应该在同一个端口上运行超过1次。然而,这不是工作,它运行…

//已编辑,更多代码…

public VentanaPropiedades() {
    initFirst();
    initComponents(); //graphic components of Matisse
}
private void initFirst() {
    loadProperties(); //just internal values of the program, nothing to do
    activateInstance();
}
private void activateInstance() throws Exception {
    try {
    final int LOCK_PORT= 54321;
    ServerSocket ss = new ServerSocket(LOCK_PORT);
    } catch (Exception e) {
        System.out.println(e);
        throw e;
    }
}
private void killProgram() {
    setVisible(false);
    dispose();
    System.exit(0);
}
private void validateInstance() {
    try {
        activateInstance();
    } catch (Exception ex) {
        killProgram();
    }
}

-------------------------- 该解决方案 ---------------------------
当第二个实例不运行时捕获的错误是:

 java.net.BindException: Address already in use: JVM_Bind 

但是,此错误并不总是发生,您可以运行同一个程序的多个实例。

不工作。类时,应该会得到一个bindeexception套接字。看看你是否不小心在某处捕获了它,或者端口是否真的不同或者类似的

ServerSocket必须在方法外部声明,就在main之后:

public class VentanaPropiedades extends javax.swing.JFrame {
    ServerSocket ss = null;
    // ... more code
}

激活方法应该使用引用:

private void activateInstance() throws Exception {
    try {
        final int LOCK_PORT= 54321;
        ss = new ServerSocket(LOCK_PORT); // note the missing "ServerSocket" before ss
    } catch (Exception e) {
        System.out.println(e);
        throw e;
    }  
}

问题是,如果您在方法中创建变量ServerSocket,那么一旦方法完成,垃圾收集器将清除它。如果变量在上面声明,垃圾收集器不会收集和清理它,因为声明的变量将保持实例化,但没有引用。

最新更新