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?

查看:111
本文介绍了Java:如何创建一个仅在不存在该实例的情况下才能启动的应用程序,并在存在该实例的情况下调用该应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java创建一个程序,该程序一次只能运行一个实例. 我正在使用Sockets和ServerSockets尝试实现这一目标.

I am trying to create a program with Java that can only have one instance of it running at a time. I am using Sockets and ServerSockets to try to achieve this.

该程序应如何工作:

main方法将检查是否传递了任何参数,它将尝试将第一个参数写入服务器,如果失败则意味着这是唯一的运行实例,因此它将打开ServerSocket并然后开始框架.如果没有失败,则表明应用程序已经在运行,因此它应该发送字符串,而另一个实例应该能够读取并处理它.

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. 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.

这是主要方法:

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();
    }
}

这是服务器类:

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?

推荐答案

在我的checkInput()方法中,您一次接受客户端连接.尝试这样的事情:

I your checkInput() method, you are accepting for client connection once here. 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();
}

一旦另一个实例启动,服务器将接受请求,进行处理,然后再次开始等待更多请求(为此我们再次称为cehckInput).

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).

也在您的main()中添加以下内容:

Also in your main() add this:

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);

这篇关于Java:如何创建一个仅在不存在该实例的情况下才能启动的应用程序,并在存在该实例的情况下调用该应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆