基于Netty4的Server和Client的简单实现==

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

基于Netty4的Server和Client的简单实现使用的Netty的版本:netty-4.0.23.Final.tar.bz2‐15-Aug-2014(Stable,Recommended)消息格式:request:Methodpath-to-resourceVersion-numberHeader-name-1:value1Header-name-2:value2Optionalrequestbodyresponse:/Version-numberresponse-coderesponse-phraseHeader-name-1:value1Header-name-2:value2Optionalresponsebody实现一个简单的请求及响应过程:1、Client向Server发送请求。2、Server端对请求进行解析。3、Server端向client发送响应。4、Client对响应进行解析。Netty中request消息格式:Netty中response消息格式:代码实例:Server:packagecom.netty.test;importorg.apache.commons.logging.Log;importorg.apache.commons.logging.LogFactory;importio.netty.bootstrap.ServerBootstrap;importio.netty.channel.ChannelFuture;importio.netty.channel.ChannelInitializer;importio.netty.channel.ChannelOption;importio.netty.channel.EventLoopGroup;importio.netty.channel.nio.NioEventLoopGroup;importio.netty.channel.socket.SocketChannel;importio.netty.channel.socket.nio.NioServerSocketChannel;importio.netty.handler.codec..RequestDecoder;importio.netty.handler.codec..ResponseEncoder;publicclassServer{privatestaticLoglog=LogFactory.getLog(Server.class);publicvoidstart(intport)throwsException{EventLoopGroupbossGroup=newNioEventLoopGroup();EventLoopGroupworkerGroup=newNioEventLoopGroup();try{ServerBootstrapb=newServerBootstrap();b.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).childHandler(newChannelInitializerSocketChannel(){@OverridepublicvoidinitChannel(SocketChannelch)throwsException{//server端发送的是Response,所以要使用ResponseEncoder进行编码ch.pipeline().addLast(newResponseEncoder());//server端接收到的是Request,所以要使用RequestDecoder进行解码ch.pipeline().addLast(newRequestDecoder());ch.pipeline().addLast(newServerInboundHandler());}}).option(ChannelOption.SO_BACKLOG,128).childOption(ChannelOption.SO_KEEPALIVE,true);ChannelFuturef=b.bind(port).sync();f.channel().closeFuture().sync();}finally{workerGroup.shutdownGracefully();bossGroup.shutdownGracefully();}}publicstaticvoidmain(String[]args)throwsException{Serverserver=newServer();log.info(Serverlisteningon8844...);server.start(8844);}}响应请求的ServerInboundHandler:packagecom.netty.test;importstaticio.netty.handler.codec..Headers.Names.CONNECTION;importstaticio.netty.handler.codec..Headers.Names.CONTENT_LENGTH;importstaticio.netty.handler.codec..Headers.Names.CONTENT_TYPE;importstaticio.netty.handler.codec..ResponseStatus.OK;importstaticio.netty.handler.codec..Version._1_1;importorg.apache.commons.logging.Log;importorg.apache.commons.logging.LogFactory;importio.netty.buffer.ByteBuf;importio.netty.buffer.Unpooled;importio.netty.channel.ChannelHandlerContext;importio.netty.channel.ChannelInboundHandlerAdapter;importio.netty.handler.codec..DefaultFullResponse;importio.netty.handler.codec..FullResponse;importio.netty.handler.codec..Content;importio.netty.handler.codec..Headers;importio.netty.handler.codec..Headers.Values;importio.netty.handler.codec..Request;publicclassServerInboundHandlerextendsChannelInboundHandlerAdapter{privatestaticLoglog=LogFactory.getLog(ServerInboundHandler.class);privateRequestrequest;@OverridepublicvoidchannelRead(ChannelHandlerContextctx,Objectmsg)throwsException{if(msginstanceofRequest){request=(Request)msg;Stringuri=request.getUri();System.out.println(Uri:+uri);}if(msginstanceofContent){Contentcontent=(Content)msg;ByteBufbuf=content.content();System.out.println(buf.toString(io.netty.util.CharsetUtil.UTF_8));buf.release();Stringres=IamOK;FullResponseresponse=newDefaultFullResponse(_1_1,OK,Unpooled.wrappedBuffer(res.getBytes(UTF-8)));response.headers().set(CONTENT_TYPE,text/plain);response.headers().set(CONTENT_LENGTH,response.content().readableBytes());if(Headers.isKeepAlive(request)){response.headers().set(CONNECTION,Values.KEEP_ALIVE);}ctx.write(response);ctx.flush();}}@OverridepublicvoidchannelReadComplete(ChannelHandlerContextctx)throwsException{ctx.flush();}@OverridepublicvoidexceptionCaught(ChannelHandlerContextctx,Throwablecause){log.error(cause.getMessage());ctx.close();}}Client:packagecom.netty.test;importio.netty.bootstrap.Bootstrap;importio.netty.buffer.Unpooled;importio.netty.channel.ChannelFuture;importio.netty.channel.ChannelInitializer;importio.netty.channel.ChannelOption;importio.netty.channel.EventLoopGroup;importio.netty.channel.nio.NioEventLoopGroup;importio.netty.channel.socket.SocketChannel;importio.netty.channel.socket.nio.NioSocketChannel;importio.netty.handler.codec..DefaultFullRequest;importio.netty.handler.codec..Headers;importio.netty.handler.codec..Method;importio.netty.handler.codec..RequestEncoder;importio.netty.handler.codec..ResponseDecoder;importio.netty.handler.codec..Version;importjava.net.URI;publicclassClient{publicvoidconnect(Stringhost,intport)throwsException{EventLoopGroupworkerGroup=newNioEventLoopGroup();try{Bootstrapb=newBootstrap();b.group(workerGroup);b.channel(NioSocketChannel.class);b.option(ChannelOption.SO_KEEPALIVE,true);b.handler(newChannelInitializerSocketChannel(){@OverridepublicvoidinitChannel(SocketChannelch)throwsException{//客户端接收到的是Response响应,所以要使用ResponseDecoder进行解码ch.pipeline().addLast(ne

1 / 7
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功