package com.ruoyi.schedule.util; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.convert.Convert; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.Socket; import java.util.Arrays; import java.util.List; import java.util.Map; public class CheckWeight { public static String sendWeight(String ip, int por) { String zhi = "0"; try ( Socket socket = new Socket(ip, por); InputStream is = socket.getInputStream(); ) { Thread.sleep(1000); byte[] bytes = new byte[100]; int read = is.read(bytes); if (read!=-1){ String[] weightList = byteArrayToCharArray(bytes, "UTF-8").split("\r\n"); System.out.println(Arrays.toString(weightList)); String weight = getMostFrequentByHutool(weightList); weight = weight.replace("=","").replace("\r","").replace("\n",""); if (!weight.equals("0000000")) { zhi = weight; } } } catch (Exception e) { e.printStackTrace(); } return zhi; } /** * 用 Hutool 找出数组中出现次数最多的字符串 * @param strArray 目标字符串数组 * @return 出现次数最多的字符串(空数组返回 null,多最大值返回第一个) */ /** * 兼容所有 Hutool 版本:找出数组中出现次数最多的字符串 * @param strArray 目标字符串数组 * @return 出现次数最多的字符串(空数组返回 null,多最大值返回第一个) */ public static String getMostFrequentByHutool(String[] strArray) { // 1. 空值校验 + 数组转 List if (strArray == null || strArray.length == 0) { return null; } List strList = CollUtil.newArrayList(strArray); // 2. 用 Hutool 统计频次(所有版本都支持) Map countMap = CollUtil.countMap(strList); // 3. 手动遍历找最大值(替代不存在的 getMaxKey 方法) String mostFrequent = null; int maxCount = 0; // 遍历 Map 条目,Hutool 5.x 及以上都支持 entrySet 遍历 for (Map.Entry entry : countMap.entrySet()) { if (entry.getValue() > maxCount) { maxCount = entry.getValue(); mostFrequent = entry.getKey(); } } return mostFrequent; } /** * 将byte数组按指定编码转为char数组 * @param byteArr 输入的byte数组 * @param charset 字符编码(如UTF-8、GBK、ASCII) * @return 转换后的char数组 * @throws UnsupportedEncodingException 编码不支持时抛出 */ public static String byteArrayToCharArray(byte[] byteArr, String charset) throws UnsupportedEncodingException { if (byteArr == null) { return null; } // 核心:先将byte数组按指定编码转为String,再转为char数组 return new String(byteArr, charset); } public static void main(String[] args) { CheckWeight checkWeight = new CheckWeight(); while (true){ System.out.println(checkWeight.sendWeight("172.19.50.80", 4001)); } } }