package com.hxzk.util.Netty; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import com.hxzk.deo.NettyPerson; import com.hxzk.pojo.TbFakaji; import com.hxzk.pojo.TbPerson; import com.hxzk.service.CabinetService; import com.hxzk.service.FaKaService; import com.hxzk.service.PersonService; import com.hxzk.service.impl.PersonServiceImpl; import com.hxzk.util.LogInFo; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.timeout.IdleStateEvent; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; import javax.annotation.Resource; import javax.annotation.Resources; import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @Component public class NettyServerHandler extends ChannelInboundHandlerAdapter { private static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); static Set channels = new HashSet<>(); static Boolean flag = false; private Integer dsq = 0; static String fetchip; static String fetchip1 = ""; private PersonService personService; private CabinetService cabinetServices; private FaKaService faKaService; public NettyServerHandler(PersonService personService1, CabinetService cabinetService,FaKaService faKaService1) { this.personService = personService1; this.cabinetServices = cabinetService; this.faKaService = faKaService1; } public NettyServerHandler() { } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (dsq == 0){ TimersDingShi(); dsq++; } Channel channel = ctx.channel(); ByteBuf buf = (ByteBuf) msg;//将 msg 转成一个 ByteBuf byte[] bytes = new byte[buf.readableBytes()]; buf.getBytes(buf.readerIndex(), bytes); buf.readBytes(bytes); InetSocketAddress insocket = (InetSocketAddress) channel.remoteAddress(); String ip = insocket.getAddress().getHostAddress(); fetchip = ip; System.out.println(fetchip); int port = insocket.getPort(); String datas = Bytes2HexString(bytes); String message1 = new String(bytes).replace(" ", "");; String s8 = "----接收数据from:" + ip + ":" + port + ":数据:" + message1; System.out.println(s8); JSONObject jsonObject = JSON.parseObject(message1);; LogInFo log = new LogInFo(); log.Info(message1); String codes = jsonObject.getString("code"); String codess = codes.replace(" ", ""); Integer code = Integer.parseInt(codess); if (code==100){ String token = jsonObject.getString("token"); // if (!token.equals("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0aW1lU3RhbXAiOjE3MjM3NzIwMzAxMTEsInVzZXJJZCI6IlwiZmdoZ2Y4ZmdqOGZnZjIza3Nkc2Q0c3I1NzgxZ2hqOGxcIiJ9.W0zHbIzX9RFADWDRpNY_hj0NSq34psi52BvA7ay7DO0")){ // System.out.println("token解析错误已断开连接"); // channel.close(); // } } try { sendMessage(message1, ip); } catch (Exception e) { e.printStackTrace(); System.out.println("接收数据"+message1+"有误"); } } public void sendMessage(String message1, String ip) { boolean validJSON = isValidJSON(message1); if (validJSON) { JSONObject jsonObject = JSON.parseObject(message1); Integer code = jsonObject.getInteger("code"); String deviceId = jsonObject.getString("deviceId"); switch (code) { case 112: try { String cmd = jsonObject.getString("cmd"); String msg1 = jsonObject.getString("msg"); String kacaoid = jsonObject.getString("doorNo"); int kacaoidDecimal = Integer.parseInt(kacaoid, 16); String kacaoidDecimalString = String.valueOf(kacaoidDecimal); String guiziid = jsonObject.getString("deviceId"); String tagid = jsonObject.getString("cardId"); String guizistate = jsonObject.getString("status"); String statics="0"; String state="0"; if (tagid.equals("0000") || tagid.equals("null")){ statics="2"; state="1"; tagid = "0000"; } TbFakaji fakaji = new TbFakaji(); fakaji.setKacaoid(kacaoidDecimalString); fakaji.setGuiziid(guiziid); fakaji.setGuizistate(guizistate); fakaji.setStatics(statics); fakaji.setState(state); fakaji.setTagid(tagid); fakaji.setUserid(""); faKaService.updateFaKaCardStatus(fakaji); System.out.println("修改上报数据成功"); }catch (Exception e){ System.out.println("数据异常"); } break; case 100: //柜子上线修改在线状态 cabinetServices.updataGuiZi(deviceId); String s0 = "100"; String jsonString1 = "{\"code\":100, \"cmd\":\"logined\", \"data\":\"null\"}"; JSONObject jsonObject1 = JSON.parseObject(jsonString1); SendMessageToClient.send(jsonObject1.toJSONString().getBytes(), jsonObject1, ip); break; // case 101: // String s1 = "101"; // List personList = personService.findAllAPIList(); // 获取所有人员数据 // int batchSize = 10; // int totalSize = personList.size(); // int fullBatches = totalSize / batchSize; // 完整的批次数量 // int remainder = totalSize % batchSize; // 剩余的数据数量 // for (int i = 0; i < fullBatches; i++) { // List batch = personList.subList(i * batchSize, (i + 1) * batchSize); // // 使用 LinkedHashMap 构造 JSON 对象以保持字段顺序 // Map dataMap = new LinkedHashMap<>(); // dataMap.put("code", 101); // dataMap.put("cmd", "send"); // dataMap.put("data", batch); // JSONObject jsonObject2 = new JSONObject(dataMap); // byte[] jsonBytes = jsonObject2.toJSONString().getBytes(StandardCharsets.UTF_8); // SendMessageToClient.send(jsonBytes, jsonObject2, ip); // } // if (remainder > 0) { // List lastBatch = personList.subList(fullBatches * batchSize, totalSize); // // // 使用 LinkedHashMap 构造 JSON 对象以保持字段顺序 // Map dataMap = new LinkedHashMap<>(); // dataMap.put("code", 101); // dataMap.put("cmd", "send"); // dataMap.put("data", lastBatch); // JSONObject jsonObject2 = new JSONObject(dataMap); // byte[] jsonBytes = jsonObject2.toJSONString().getBytes(StandardCharsets.UTF_8); // SendMessageToClient.send(jsonBytes, jsonObject2, ip); // } // break; case 102: String s2 = "102"; Map dataMap2 = new LinkedHashMap<>(); dataMap2.put("code", 102); dataMap2.put("cmd", "delete"); dataMap2.put("data", new LinkedHashMap() {{ put("name", "John"); put("age", 30); }}); JSONObject jsonObject3 = new JSONObject(dataMap2); SendMessageToClient.send(s2.getBytes(), jsonObject3, ip); break; case 103: String s3 = "103"; Map dataMap3 = new LinkedHashMap<>(); dataMap3.put("code", 103); dataMap3.put("cmd", "openDoor"); dataMap3.put("data", "doorNo"); JSONObject jsonObject4 = new JSONObject(dataMap3); SendMessageToClient.send(s3.getBytes(), jsonObject4, ip); break; case 104: String s4 = "104"; Map dataMap4 = new LinkedHashMap<>(); dataMap4.put("code", 104); dataMap4.put("cmd", "upDate"); dataMap4.put("data", "http://upload.huiningdianzi.cn/update.bin"); JSONObject jsonObject5 = new JSONObject(dataMap4); SendMessageToClient.send(s4.getBytes(), jsonObject5, ip); break; } } } //数据读取完毕 @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { } //处理异常, 一般是需要关闭通道 @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { } @SuppressWarnings("unused") @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { //将 evt 向下转型 IdleStateEvent IdleStateEvent event = (IdleStateEvent) evt; String eventType = null; switch (event.state()) { case READER_IDLE: eventType = "读空闲"; break; case WRITER_IDLE: eventType = "写空闲"; break; case ALL_IDLE: eventType = "读写空闲"; break; } InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress(); StringBuffer ip = new StringBuffer(insocket.getAddress().getHostAddress()); //如果发生空闲,我们关闭通道 //ctx.channel().close(); } } /** * 将字节数组转为16进制字符串 */ public static String Bytes2HexString(byte[] b) { String ret = ""; for (int i = 0; i < b.length; i++) { String hex = Integer.toHexString(b[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } ret += hex.toUpperCase(); } return ret; } public void kaisuo(String doorNo){ if (fetchip1.equals("") || fetchip1 == null){ fetchip1 = fetchip; } String s3 = "103"; Map dataMap3 = new LinkedHashMap<>(); dataMap3.put("code", 103); dataMap3.put("cmd", "openDoor"); dataMap3.put("data", doorNo); JSONObject jsonObject4 = new JSONObject(dataMap3); SendMessageToClient.send(jsonObject4.toJSONString().getBytes(), jsonObject4, fetchip1); } public void shengji(){ if (fetchip1.equals("")){ fetchip1 = fetchip; } String s4 = "104"; Map dataMap4 = new LinkedHashMap<>(); dataMap4.put("code", 104); dataMap4.put("cmd", "upDate"); dataMap4.put("data", "http://upload.huiningdianzi.cn/update.bin"); JSONObject jsonObject5 = new JSONObject(dataMap4); SendMessageToClient.send(jsonObject5.toJSONString().getBytes(), jsonObject5, fetchip1); } public void xiafa(PersonService personServices) { String s1 = "101"; List personList = personServices.findAllAPIList(); // 获取所有人员数据 int batchSize = 10; int totalSize = personList.size(); int fullBatches = totalSize / batchSize; // 完整的批次数量 int remainder = totalSize % batchSize; // 剩余的数据数量 for (int i = 0; i < fullBatches; i++) { List batch = personList.subList(i * batchSize, (i + 1) * batchSize); String jsonString = createJsonMessage(batch); // 转换为UTF-8编码 byte[] utf8Bytes = jsonString.getBytes(StandardCharsets.UTF_8); SendMessageToClient.send(utf8Bytes, null, fetchip); // 假设send方法可以直接发送字节数据 } if (remainder > 0) { List lastBatch = personList.subList(fullBatches * batchSize, totalSize); String jsonString = createJsonMessage(lastBatch); // 转换为UTF-8编码 byte[] utf8Bytes = jsonString.getBytes(StandardCharsets.UTF_8); SendMessageToClient.send(utf8Bytes, null, fetchip); } System.out.println("下发成功"); } private String createJsonMessage(List batch) { LinkedHashMap map = new LinkedHashMap<>(); map.put("code", 101); map.put("cmd", "send"); map.put("data", batch); JSONObject jsonObject = new JSONObject(map); System.out.println(jsonObject); return jsonObject.toJSONString(); } public static Set getChannels() { return channels; } /** * 判断字符串是否为有效的 JSON 格式 * @param jsonString 待判断的字符串 * @return 如果是有效的 JSON 格式返回 true,否则返回 false */ public static boolean isValidJSON(String jsonString) { try { JSON.parse(jsonString); return true; } catch (JSONException e) { return false; } } public static void startScheduledTask(long initialDelay, long period, Runnable task) { scheduler.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.MILLISECONDS); } public String TimersDingShi(){ startScheduledTask(1000, 60000, () -> cabinetServices.updataGuiZiAll()); return "开始执行定时器更改柜子状态"; } }