简体   繁体   English

Java:如何创建一个应用程序,该应用程序仅在它的实例不存在时才启动,并在实例存在时调用该实例?

[英]Java: How can I create an application that will only start if an instance of it doesn't exist and call the instance if it does exist?

I am trying to create a program with Java that can only have one instance of it running at a time.我正在尝试使用 Java 创建一个程序,该程序一次只能运行一个实例。 I am using Sockets and ServerSockets to try to achieve this.我正在使用 Sockets 和 ServerSockets 来尝试实现这一点。

How the program is supposed to work is:该程序应该如何工作:

The main method will check if any parameters have been passed, it will try to write the first parameter to the server, if it fails that means, that means that this is the only running instance, so it will open the ServerSocket and then start the frame. main 方法会检查是否有任何参数被传递,它会尝试将第一个参数写入服务器,如果失败则意味着这是唯一运行的实例,因此它将打开 ServerSocket 然后启动服务器框架。 If it doesn't fail then the application is already running so it should send the string and the other instance should be able to read it and process it.如果它没有失败,那么应用程序已经在运行,所以它应该发送字符串,另一个实例应该能够读取它并处理它。

Here's the main method:下面是主要方法:

public static void main(String[] args) {
    String fileName = null;
    if (args.length >= 1) {
        fileName = args[0];
    }
    if (Singleton.sendSignal(fileName)) {
        Frame.getFrame().open(fileName);
        Singleton.checkInput();
    }
}

And here's the server class:这是服务器类:

public class Singleton {
    private static final int portNumber = 4243;
    private static ServerSocket serverSocket;
    private static Socket clientSocket;
    private static Socket echoSocket;

    public static boolean sendSignal() {
        try {
            echoSocket = new Socket(InetAddress.getLocalHost().getHostName(), portNumber);
            PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
            out.write("Open\n");
            out.close();
            close();
            return false;
        } catch (Exception e) {
            close();
            return true;
        }
    }

    public static void checkInput() {
        try {
            renewReader();
        } catch (Exception e) {
            close();
        }
    }

    public static void renewReader() throws Exception {
        serverSocket = new ServerSocket(portNumber);
        clientSocket = serverSocket.accept();
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String inputLine = in.readLine();
        if (inputLine.equals("Open")) {
            Widget.getInstance().setVisible(true);
        }
        close();
        renewReader();
    }

    public static void close() {
        try {
            serverSocket.close();
        } catch (Exception e) {
        }
        try {
            clientSocket.close();
        } catch (Exception e) {
        }
        try {
            echoSocket.close();
        } catch (Exception e) {
        }
    }

}

Although half of this code works (only one instance runs at a time), only the first set of data are being passed and then the program stops reading.尽管此代码的一半有效(一次仅运行一个实例),但仅传递第一组数据,然后程序停止读取。 How can I make the socket listen until the program is closed?如何让套接字监听直到程序关闭?

I your checkInput() method, you are accepting for client connection once here.我是你的 checkInput() 方法,你在这里接受客户端连接。 Try something like this:尝试这样的事情:

public static void checkInput() 
{   
     //do something here
     serverSocket = new ServerSocket(portNumber);
     //wait for request from client.
     Socket clientSocket = serverSocket.accept();
     //
     // do your processing here

     // call checkInput method again.
     checkInput();
}

As soon as another instance it started, server will accept the request, do the processing and then again starts waiting for more requests (for this we called cehckInput again).一旦另一个实例启动,服务器将接受请求,进行处理,然后再次开始等待更多请求(为此,我们再次调用了 cehckInput)。

Also in your main() add this:同样在您的 main() 中添加:

public static void main(String[] args) 
{
    String fileName = null;
    if (args.length >= 1) {
        fileName = args[0];
    }
    if (Singleton.sendSignal(fileName)) 
    {
        Frame.getFrame().open(fileName);

        // start the server in a thread so that main method can continue on
        new Thread()
        {
           public void run()
           {
                Singleton.checkInput();
           }
        }.start();
    }

    // do your other tasks.
}

On upon termination of program, your sockets will auto close.在程序终止时,您的套接字将自动关闭。 Also if you want to explicitly close the sockets, you can add a shutdown hook to close it.此外,如果您想明确关闭套接字,您可以添加一个关闭钩子来关闭它。 A simple hook looks like this.一个简单的钩子看起来像这样。

Runtime.getRuntime().addShutdownHook(your thread that will close sockets);

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

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