[英]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?
我正在嘗試使用 Java 創建一個程序,該程序一次只能運行一個實例。 我正在使用 Sockets 和 ServerSockets 來嘗試實現這一點。
該程序應該如何工作:
main 方法會檢查是否有任何參數被傳遞,它會嘗試將第一個參數寫入服務器,如果失敗則意味着這是唯一運行的實例,因此它將打開 ServerSocket 然后啟動服務器框架。 如果它沒有失敗,那么應用程序已經在運行,所以它應該發送字符串,另一個實例應該能夠讀取它並處理它。
下面是主要方法:
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) {
}
}
}
盡管此代碼的一半有效(一次僅運行一個實例),但僅傳遞第一組數據,然后程序停止讀取。 如何讓套接字監聽直到程序關閉?
我是你的 checkInput() 方法,你在這里接受客戶端連接。 嘗試這樣的事情:
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)。
同樣在您的 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.
}
在程序終止時,您的套接字將自動關閉。 此外,如果您想明確關閉套接字,您可以添加一個關閉鈎子來關閉它。 一個簡單的鈎子看起來像這樣。
Runtime.getRuntime().addShutdownHook(your thread that will close sockets);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.