netty客户端实现和服务端实现

 1 解决拆包,粘包问题

https://www.cnblogs.com/sidesky/p/6913109.html

  2 解决心跳问题 

https://www.cnblogs.com/demingblog/p/9957143.html

HttpServerCodec() 解码和编码http请求

自己实现
HttpHandler extend simpleChannelInboundHandler<FullHttpRequest>
并实现channelRead0

使用了pipe.addlast(new simpleChannelInboundHandler必须添加httpObjectAggretor(64*1024))

channelInboundHanderAdapter

获取根目录 httpHandler.class.getCodeSource().getLocation()

simpleChannelInboundHandler<TextWebSocketFrame>

IMEncoder Extends MessageToByTeEncoder<IMMessage>{

	@Overide
	encode(ctx,IMMessage msg,ByteBuf out){
		out.writeBytes(new messagePack.write(msg))
	}
}

关闭网页
public void handlerRemoved(ChanneHanderContext ctx){
	processor.logout();
}

//反序列化
IMDecoder extends ByteToMessageDecoder{

	@decode
	protect void decode(ctx,ByteBuf in,list<Obj> out){
	
		 final int lenth= in.readableBytes();
		 final byte[] array = new byte[lenth];
		 
		 String content = new String(arry,in.readableBytes,lenth);
		 if(StringUtils.isEmpty(content)){
			
		 }
		 
		 //反序列过程
		 in.getBytes()(in.readableBytes(),arry,0,lenth);
		 
		 //首先自己转为MessagePack,再把这个Msg转为IMMessage
		 out.add(new MessagePack().read(arry,IMMessage.class));
		 in.clear();
		 
	}
	
}

//序列化
EnCoder Extends MessageToByteEncoder<IMMessage>{
	@encode
	
	public void encode(ctx,IMMessage msg,ByteBuf out){
	
		//IMMessage 对象序列化MsgPack
		out.writeBytes(new MessagePack().write(msg))
	}
}

msgpack





SocketHandler extend simpleChannelInboundHandler<IMMessage>

chatClientHandler extends ChannelInboudHandlerAdapter{

}


public boolean sendMsg(IMMessage msg){
	ctx.channel.writeAndFlush(msg);
}



发布了62 篇原创文章 · 获赞 5 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/yingcly003/article/details/99353938