kill 上线

This commit is contained in:
jianguo 2024-05-28 17:36:27 +08:00
parent 9dddeeccf8
commit 3bec2895b1
3 changed files with 63 additions and 7 deletions

View File

@ -1,10 +1,12 @@
package org.aohe.core.swing;
import lombok.extern.slf4j.Slf4j;
import org.aohe.core.utils.CommandUtils;
import org.aohe.core.web.SocketFactory;
import javax.swing.*;
import java.awt.*;
import java.util.List;
@Slf4j
public class MainWindow extends JFrame {
@ -55,6 +57,7 @@ public class MainWindow extends JFrame {
startButton.addActionListener(e -> {
startButton.setEnabled(false);
stopButton.setEnabled(true);
CommandUtils.killUsedPort("8997");
initSocket();
setView("服务已打开...");
serviceStatus = true;
@ -125,6 +128,11 @@ public class MainWindow extends JFrame {
}
}
public boolean checkPort(String port){
List<CommandUtils.LsofInfo> lsofInfos = CommandUtils.findPort(port);
return !lsofInfos.isEmpty();
}
public static void setView(String msg){
if(logTextArea != null){
logTextArea.append(msg +"\n");

View File

@ -2,6 +2,8 @@ package org.aohe.core.utils;
import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import java.nio.charset.StandardCharsets;
@ -59,4 +61,57 @@ public class CommandUtils {
return result;
}
public static void killUsedPort(String port){
List<LsofInfo> lsofInfos = findPort(port);
for(LsofInfo lsofInfo : lsofInfos){
destroy(lsofInfo.getPid());
}
}
public static List<LsofInfo> findPort(String port){
String exec = StrUtil.format("lsof -i:{}",port);
String s = execForStrUtf8Sudo(exec);
return parseCommandOutput(s);
}
public static void destroy(String pid){
String exec = StrUtil.format("kill -9 {}",pid);
execForStrUtf8Sudo(exec);
}
/**
* lsof 格式化
* @param output s
* @return list
*/
public static List<LsofInfo> parseCommandOutput(String output) {
List<LsofInfo> processInfos = new ArrayList<>();
String[] lines = output.split("\n");
if(lines.length <= 1){
return new ArrayList<>();
}
for (int i = 1 ; i < lines.length ; i ++) {
//从第一行开始
String[] parts = lines[i].trim().split("\\s+");
if (parts.length < 6) {
return new ArrayList<>();
}
LsofInfo processInfo = new LsofInfo();
processInfo.setPid(parts[1]);
processInfo.setType(parts[4]);
processInfos.add(processInfo);
}
return processInfos;
}
@Data
@ToString
public static class LsofInfo {
private String pid;
private String type;
}
}

View File

@ -1,18 +1,11 @@
package org.aohe.core.utils;
import cn.hutool.core.net.Ipv4Util;
import cn.hutool.core.net.NetUtil;
import org.aohe.core.sane.utils.SaneSessionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.*;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class SystemUtils {