From 21d9c3bc966266a76b8f43f9a4729d791bb9f6bd Mon Sep 17 00:00:00 2001 From: "zhangzc@shuhua.com" <12345678> Date: Thu, 22 Jun 2017 16:51:39 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8D=E6=96=B0=E6=8B=86=E5=8C=85=E6=96=B9?= =?UTF-8?q?=E6=B3=95=EF=BC=8C=E4=B8=8Ebytebuf=E8=A7=A3=E8=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../server/encoder/ToModelEncoder.java | 28 ++++++++++++++++--- .../cn/_94zichao/server/util/ByteUtil.java | 20 ++++++------- 2 files changed, 34 insertions(+), 14 deletions(-) diff --git a/src/main/java/cn/_94zichao/server/encoder/ToModelEncoder.java b/src/main/java/cn/_94zichao/server/encoder/ToModelEncoder.java index f80091d..82e30cf 100644 --- a/src/main/java/cn/_94zichao/server/encoder/ToModelEncoder.java +++ b/src/main/java/cn/_94zichao/server/encoder/ToModelEncoder.java @@ -7,6 +7,10 @@ import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + /** * Created by zzc on 2017/5/16. * @@ -24,11 +28,27 @@ public class ToModelEncoder extends MessageToByteEncoder { */ @Override protected void encode(ChannelHandlerContext ctx, byte[] msg, ByteBuf out) throws Exception { - - for (int i = 0; i < msg.length; i++) { - ByteUtil.writeByte(out,msg[i]); + byte[] all = new byte[256]; + int i = 1; + int j = 1; + all[0] = msg[0]; + while (true){ + if (i == msg.length-1){ + break; + } + byte cur =msg[i]; + byte[] bytes = ByteUtil.writeByte(cur); + if (bytes[0] != cur){ + all[j++] = bytes[0]; + all[j++] = bytes[1]; + i++; + }else { + all[j++] = msg[i++]; + } } - out.writeByte(Content.END); + all[j++] = msg[i]; + out.writeBytes(ByteUtil.getBytes(all,0,j)); + } } diff --git a/src/main/java/cn/_94zichao/server/util/ByteUtil.java b/src/main/java/cn/_94zichao/server/util/ByteUtil.java index d95533d..79e0298 100644 --- a/src/main/java/cn/_94zichao/server/util/ByteUtil.java +++ b/src/main/java/cn/_94zichao/server/util/ByteUtil.java @@ -34,29 +34,29 @@ public class ByteUtil { byte[] temp = new byte[buf.readableBytes()]; temp[0] = buf.readByte(); int i; - for (i= 1;i>3)==0){ - buf.writeByte((byte)0xf7); - buf.writeByte(bytes & (byte)0x0f); + all[0]=(byte)0xf7; + all[1]=(byte)(bytes & (byte)0x0f); }else { - buf.writeByte(bytes); + all[0]= bytes; } + return all; } /** @@ -105,8 +105,8 @@ public class ByteUtil { * @return */ public static byte[] getBytes(byte[] data,int start,int end){ - byte[] all = new byte[end-start-1]; - System.arraycopy(data, start + 1, all, 0, end - start - 1); + byte[] all = new byte[end-start]; + System.arraycopy(data, start , all, 0, end - start); return all; }