步骤 2 : 使用 package util;
import java.io.IOException;
import java.net.ServerSocket;
public class PortUtil {
public static final int application_port = 3003;
public static boolean testPort(int port) throws PortException {
try {
ServerSocket ss = new ServerSocket(port);
ss.close();
return true;
} catch (Exception e) {
// TODO Auto-generated catch block
// e.printStackTrace();
throw new PortException(port);
}
}
public static void usePort(int port) throws PortException {
try {
ServerSocket ss = new ServerSocket(port);
new Thread() {
public void run() {
try {
ss.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
// ss.accept();
} catch (Exception e) {
// TODO Auto-generated catch block
// e.printStackTrace();
throw new PortException(port);
}
}
public static void check(int port) throws PortException {
int port80 = port;
if (!testPort(port80))
throw new PortException(port80);
}
}
package util;
public class PortException extends Exception {
int port;
public PortException(int port) {
this.port = port;
}
public String toString() {
String result = String.format("%s 端口被占用", String.valueOf(port));
return result;
}
}
try {
PortUtil.usePort(PortUtil.application_port);
} catch (PortException e1) {
JOptionPane.showMessageDialog(null, "已经启动");
return;
}
try { PortUtil.usePort(PortUtil.application_port); } catch (PortException e1) { JOptionPane.showMessageDialog(null, "已经启动"); return; }
HOW2J公众号,关注后实时获知最新的教程和优惠活动,谢谢。
提问之前请登陆
提问已经提交成功,正在审核。 请于 我的提问 处查看提问记录,谢谢
|