解决netty客户端接收报文不完整的情况

时间:2025-04-05 09:16:53
1 public class EsbClientHandler extends ChannelHandlerAdapter { 2 3 private static Logger logger = (EsbClientHandler.class); 4 5 private ByteBuf byteMsg; 6 7 private boolean flag; 8 9 /** 10 * 临时客户端数据key 11 */ 12 private String key = "key"; 13 14 public EsbClientHandler(String xml, String key, boolean flag) { 15 this.key = key; 16 this.flag = flag; 17 byte[] req = null; 18 try { 19 req = ("UTF-8"); 20 } catch (UnsupportedEncodingException e) { 21 (); 22 } 23 byteMsg = (); 24 (req); 25 } 26 27 @Override 28 public void channelActive(ChannelHandlerContext ctx) throws Exception { 29 (byteMsg); 30 } 31 32 @Override 33 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 34 try { 35 ByteBuf buf = (ByteBuf) msg; 36 byte[] req = new byte[()]; 37 (req); 38 String body = new String(req, "UTF-8"); 39 flag = true; 40 String xml = (body); 41 analysisXml(xml); 42 } catch (Exception e) { 43 (); 44 } finally { 45 (msg); 46 } 47 48 } 49 50 @Override 51 public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 52 (); 53 if (flag) { 54 (); 55 } else { 56 (); 57 } 58 } 59 60 @Override 61 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 62 // 释放资源 63 (); 64 } 65 66 /** 67 * 68 * 客户端解析服务端返回的xml数据,进行数据操作 69 * 70 * @param xml 71 */ 72 public void analysisXml(String xml) { 73 ("获取服务器接收报文:" + xml); 74 ("开始解析xml:"); 75 (xml); 76 (key, xml); 77 } 78 }