网络编程复习(六):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 ChannelInitializer
() { @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(); }}
serverHandler处理类:

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 ChannelInitializer
() { @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(); }}
clientHandler事件处理类

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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:网络编程复习(七):Netty解决拆包粘包问题--分隔符方式
下一篇:网络编程复习(五):Socket编程中的IO模式详解

发表评论

最新留言

不错!
[***.144.177.141]2024年03月31日 03时04分50秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章

《华尔街之狼》精髓:摔倒并不是坏事,就怕你因此放弃。 2019-04-26
《微观动机与宏观行为》精髓:个人的微观动机,是如何影响宏观行为结果的? 2019-04-26
《国富论》精髓:亚当·斯密提出的对后世影响深远的三个经济学理论:劳动分工理论、生产要素理论和宏观调控理论 2019-04-26
《动荡的世界》精髓:什么是动物精神?动物精神又是怎么影响2008年全球经济危机的,以及我们该如何预防动物精神,避免危机再次发生。 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
《曾国藩的经济课》书中的精髓:我们如何像曾国藩一样,在遇到道德和环境冲突时,既能保持自己的道德,又能调动资源,帮助自己成事。 2019-04-26
《富人的逻辑》书中的精髓:为什么暴富起来的人会在短期内失去财富,我们又该如何去创造财富和持续拥有财富。 2019-04-26
作文提升~老师整理的优美比喻句太实用 2019-04-26
作文提升~老师整理的优美拟人句太实用 2019-04-26
作文提升~老师整理的优美排比句太实用 2019-04-26