网络编程复习(六):Netty入门Demo
发布日期:2021-11-13 10:21:51
浏览次数:11
分类:技术文章
本文共 4540 字,大约阅读时间需要 15 分钟。
关于Netty,可以看做是对JDK的nio API的封装,提供了更简单的实现,同时性能,功能更加丰富以及相对应的安全机制,对于Netty的学习,大家可以访问如下网址,里面讲解的很详细,这里仅写一个小demo作为入门。
学习网址:http://ifeve.com/netty5-user-guide/
server:
package 网络编程_Netty;import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelOption;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioServerSocketChannel;public class Server { private int port; public Server(int port){ this.port = port; } public void run() throws Exception{ /*定义两个处理IO操作的多线程时间循环器,boss一般用来接受客户端连接,workers用来处理已经被接 收的连接,这里使用NIOEvent处理tcp协议,还有很多种实现类用于处理不同的传输协议。 */ EventLoopGroup boss = new NioEventLoopGroup(); EventLoopGroup workers = new NioEventLoopGroup(); try { //ServerBootstrap是服务端的启动NIO服务的辅助类,用于设置一些服务的参数 ServerBootstrap bootstrap = new ServerBootstrap(); //将两个事件循环器加入到辅助类中 bootstrap.group(boss, workers) //指定具体的通道连接方式 .channel(NioServerSocketChannel.class) //使用childHandler指定具体的事件处理类 .childHandler(new ChannelInitializerserverHandler处理类:() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ServerHandler()); } }) //关闭BACKLOG参数作用需要了解TCP底层三次握手机制,底部维持了2个队列,当两个队列和大于BACKLOG时,服务端会拒绝客户端连接 .option(ChannelOption.SO_BACKLOG, 128) //保持存活状态 .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = bootstrap.bind(port).sync();//绑定端口 f.channel().closeFuture().sync();//相当于阻塞 } finally { workers.shutdownGracefully();//关闭操作 boss.shutdownGracefully(); } } public static void main(String[] args) throws Exception{ new Server(8888).run(); }}
package 网络编程_Netty;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelFutureListener;import io.netty.channel.ChannelHandlerAdapter;import io.netty.channel.ChannelHandlerContext;/** * 处理器类,处理器是由netty生成用来处理IO事件的 * @author lihao * */public class ServerHandler extends ChannelHandlerAdapter{ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf)msg; byte[] bys = new byte[buf.readableBytes()]; buf.readBytes(bys); String accept = new String(bys,"utf-8"); System.out.println(accept); String response = new String("你好,服务器已经接受到你的请求"); ChannelFuture writeAndFlush = ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));//wirte的时候会手动的释放msg writeAndFlush.addListener(ChannelFutureListener.CLOSE);//监听写数据进程,当数据写出完毕关闭连接 } }client:
package 网络编程_Netty;import io.netty.bootstrap.Bootstrap;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelInitializer;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioSocketChannel;public class Client { public static void main(String[] args) throws Exception { EventLoopGroup workers = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(workers) .channel(NioSocketChannel.class) .handler(new ChannelInitializerclientHandler事件处理类() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ClientHandler()); } }); ChannelFuture f = bootstrap.connect("127.0.0.1",8888).sync(); f.channel().writeAndFlush(Unpooled.copiedBuffer("hello netty".getBytes())); f.channel().closeFuture().sync(); workers.shutdownGracefully(); }}
package 网络编程_Netty;import io.netty.buffer.ByteBuf;import io.netty.channel.ChannelHandlerAdapter;import io.netty.channel.ChannelHandlerContext;import io.netty.util.ReferenceCountUtil;public class ClientHandler extends ChannelHandlerAdapter{ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try { ByteBuf buf = (ByteBuf)msg; byte[] bys = new byte[buf.readableBytes()]; buf.readBytes(bys); String accept = new String(bys,"utf-8"); System.out.println(accept); } finally { ReferenceCountUtil.release(msg); } } }
转载地址:https://blog.csdn.net/Lee_Ho_/article/details/78128340 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
不错!
[***.144.177.141]2024年03月31日 03时04分50秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
《华尔街之狼》精髓:摔倒并不是坏事,就怕你因此放弃。
2019-04-26
《微观动机与宏观行为》精髓:个人的微观动机,是如何影响宏观行为结果的?
2019-04-26
《周期》书中的精髓:如何利用周期,掌握世界的发展趋势,实现财富积累。
2019-04-26
《伟大的博弈》书中的精髓:华尔街是如何从一条小街,一步步发展为世界金融中心的。
2019-04-26
《逃不开的经济周期》书中的精髓:经济周期是推动创新变革和经济增长以及复兴的关键力量。
2019-04-26
《动物精神》书中的精髓:人类的非理性面影响经济决策,这些有可能是金融危机的根源。
2019-04-26
《巴菲特法则》书中的精髓:用好巴菲特企业前景投资法则,股票投资稳赚不赔。
2019-04-26
《战胜华尔街》书中的精髓:业余投资者如何根据行业特点选好股票,赚得比专业的投资者还要多?
2019-04-26
《股市稳赚》书中的精髓:用简单的神奇公式进行股票投资,获得稳定而持久的收益。
2019-04-26
作文提升~老师整理的优美比喻句太实用
2019-04-26
作文提升~老师整理的优美拟人句太实用
2019-04-26
作文提升~老师整理的优美排比句太实用
2019-04-26