很簡單直覺,java限制雙開的程式寫法

private static final int PORT = 9999;
private static ServerSocket socket;    

private static void main() {
  try {
    //Bind to localhost adapter with a zero connection queue 
    socket = new ServerSocket(PORT,0,InetAddress.getByAddress(new byte[] {127,0,0,1}));
    // 正常流程
    //
  }
  catch (BindException e) {
    // 異常流程
    System.err.println("Already running.");
    System.exit(1);
    Runtime.getRuntime().halt(0);
  }
}

發表迴響