@Override public void channelRead0(final ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf in = (ByteBuf) msg; byte[] bytes = in.array(); String sInfo = Hex.encodeHexStr(bytes); logger.info(String.format("primary received:%s", sInfo)); // 接收到包的长度 int length = in.readableBytes(); // 终端设备上报到服务器位始 $$ String head = in.readBytes(2).toString(Charset.defaultCharset()); if ("$$".equals(head)) { // 从包的字段得到包的长度 short l = in.readShort(); System.out.println(l); if (length == l) { // 得到产品id 序列号 final String serialNumber = byteToArray(in.readBytes(7).array()); // 得到协议号 final String agreement = byteToArray(in.readBytes(2).array()); // 得到数据 final String content = operation(serialNumber, head, length, l, agreement, in, ctx); // 得到校验位 checksum String checksum = byteToArray(in.readBytes(2).array()); // 得到结束符\r\n final String end = byteToArray(in.readBytes(2).array()); executorService.execute( new Runnable() { public void run() { try { serviceHandler(ctx, serialNumber, agreement, content, end); } catch (Exception e) { e.printStackTrace(); } } }); } } }
protected void serviceHandler( ChannelHandlerContext ctx, String serialNumber, String agreement, String content, String end) throws Exception { /* * 子服务器的ip和端口(根据子服务器的ip和端口,可以做随机下发子服务器,然后设备根据你下发的信息,去连接子服务器) */ String ip = "120.24.176.185"; int port = 8075; if ("0002".equals(agreement)) { String info = "40400023" + serialNumber + agreement + Hex.encodeHexStr((ip + ":" + port).getBytes()); // 返回消息给终端 returnMessage(info, ctx, end); Info in = infoDao.findBySerialNumber(serialNumber); if (in != null) { in.setIp(ip); in.setPort(port); infoDao.updateInfo(in); } else { Info i = new Info(); i.setIp(ip); i.setPort(port); i.setSerialNumber(serialNumber); infoDao.addInfo(i); } if (sndao.findBySerialNumber(serialNumber) != null) { logger.info("SerialNumber has registered"); } else { SerialNumber serialNum = new SerialNumber(); serialNum.setSerialNumber(serialNumber); serialNum.setEf("3"); sndao.addSerialNumber(serialNum); logger.info("new SerialNumber, SerialNumber added"); } } }