Detect another program running status by using socket
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketException;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class MyFrame extends JFrame {
private ServerSocket ss;
public MyFrame() {
try {
// create a new socket and bind it to listen
ss = new ServerSocket();
ss.bind(new InetSocketAddress(100));
} catch (SocketException e) {
// if this socket is in using, presume the program is running
JOptionPane.showMessageDialog(this, "Application already in running.");
System.exit(1);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Application encountered some problem.");
System.exit(1);
}
this.getContentPane().add(new JLabel("Hello world!"));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(300, 300);
this.setLocation(300, 300);
this.setVisible(true);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new MyFrame();
}
}