当前位置: 首页 > news >正文

Netty(一)之helloworld

HelloWorld

客户端通向服务器端发送消息,服务器端读取数据(你好)并且返回(new Date()),客户端读取数据

pom

<dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>5.0.0.Alpha1</version> </dependency>

TimeServerHandler

服务器端读取数据并且回应请求,继承ChannelHandlerAdapter并且实现channelRead和exceptionCaught方法

package myhelloworld; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import java.util.Date; /** * @author CBeann * @create 2019-08-27 18:31 */ public class TimeServerHandler extends ChannelHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { //服务器读客户端发送来的数据 ByteBuf buf = (ByteBuf) msg; byte[] req = new byte[buf.readableBytes()]; buf.readBytes(req); String body = new String(req, "UTF-8"); System.out.println("The TimeServer receive :" + body); //服务器向客户端回应请求 ByteBuf response = Unpooled.copiedBuffer(new Date().toString().getBytes()); ctx.writeAndFlush(response); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); } // }

TimeServer

package myhelloworld; 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; /** * @author CBeann * @create 2019-08-27 18:22 */ public class TimeServer { public static void main(String[] args) throws Exception { int port = 8080; //配置服务器端的NIO线程组 EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { //TimeClientHandler是自己定义的方法 socketChannel.pipeline().addLast(new TimeServerHandler()); } }); //绑定端口 ChannelFuture f = b.bind(port).sync(); //等待服务端监听端口关闭 f.channel().closeFuture().sync(); } catch (Exception e) { } finally { //优雅关闭,释放线程池资源 bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }

启动NettyServer的模版代码

private void bing(int port) { EventLoopGroup parentGroup = new NioEventLoopGroup(); EventLoopGroup childGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(parentGroup, childGroup) .channel(NioServerSocketChannel.class) //非阻塞模式 .option(ChannelOption.SO_BACKLOG, 128) .childHandler(new MyChannelInitializer()); ChannelFuture f = b.bind(port).sync(); System.out.println("itstack-demo-netty server start done. {关注公众号:bugstack虫洞栈,获取源码}"); f.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { childGroup.shutdownGracefully(); parentGroup.shutdownGracefully(); } }

TimeClientHandler

客户端读取服务器响应数据,继承ChannelHandlerAdapter并且实现channelRead和exceptionCaught方法

package myhelloworld; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; import io.netty.util.ReferenceCountUtil; /** * @author CBeann * @create 2019-08-27 18:47 */ public class TimeClientHandler extends ChannelHandlerAdapter { //客户端读取服务器发送的数据 @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try { ByteBuf buf = (ByteBuf) msg; byte[] req = new byte[buf.readableBytes()]; buf.readBytes(req); String body = new String(req, "UTF-8"); System.out.println("Now is:" + body); } catch (Exception e) { } finally { //标配 ReferenceCountUtil.release(msg); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); } }

TimeClient

package myhelloworld; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.Unpooled; 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.NioSocketChannel; /** * @author CBeann * @create 2019-08-27 18:43 */ public class TimeClient { public static void main(String[] args) throws Exception { int port = 8080; String host = "127.0.0.1"; //配置客户端NIO线程组 EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { //TimeClientHandler是自己定义的方法 socketChannel.pipeline().addLast(new TimeClientHandler()); } }); //发起异步连接操作 ChannelFuture f = b.connect(host, port).sync(); //发送数据 f.channel().writeAndFlush(Unpooled.copiedBuffer("您好".getBytes())); //Thread.sleep(1000);//防止TCP粘包 //f.channel().writeAndFlush(Unpooled.copiedBuffer("您好".getBytes())); //Thread.sleep(1000); //f.channel().writeAndFlush(Unpooled.copiedBuffer("您好".getBytes())); //Thread.sleep(1000); //等待客户端链路关闭 f.channel().closeFuture().sync(); } catch (Exception e) { } finally { //优雅关闭 group.shutdownGracefully(); } } }

学习总结

1)自己敲一遍,因为不确定你查询到的博客是对还是错的

2)很多地方都是固定格式,需要修改的地方就那么几个

2.1)option(ChannelOption.SO_BACKLOG, 1024) 修改一些参数

2.2)socketChannel.pipeline().addLast(new TimeServerHandler())添加一些自己定义或者系统的handler

2.3)自己定义的handler

3)请坚持

http://www.jsqmd.com/news/1282226/

相关文章:

  • dubbo实战01-入门案例
  • 开源模型成本陷阱全曝光,92%团队踩坑的3类隐性开销(CUDA版本兼容性、KV Cache内存泄漏、Tokenizer序列膨胀)
  • 终极鼠标优化方案:让你的普通鼠标在macOS上超越苹果触控板体验
  • 别把Tg等同于耐温上限!采购PCB板材真实作用
  • 版本的比较(java)
  • LeetCode515. 在每个树行中找最大值
  • for in
  • 2026邢台黄金回收就来丽坤奢品汇18617962974全国连锁专业靠谱 - 丽坤奢品汇
  • 羽毛球 AI 方案选型对比:MediaPipe vs YOLOv8-Pose vs OpenPose 在运动分析场景的精度与延迟评估
  • Netty简介及使用
  • NLTK获取停用词
  • 北京东城实测专项整治虚高报价引流到店压价可投诉 - 生活时报
  • 全国武校升学率排名,圣龙武术学校学员去向 - 圣龙武术朱老师
  • Godot Shader特效:3D描边(outline)效果 原理篇
  • 计算机毕业设计之《计算机网络》课程微信小程序
  • TTS-Backup终极指南:守护你的桌游模拟器珍贵数据
  • vue 复习02
  • 速卖通商品详情接口实战指南:官方合规调用与全维度数据解析
  • Python简单介绍及环境搭建
  • 武校收费标准查询方式,石家庄圣龙武术学校咨询电话 - 圣龙武术朱老师
  • 游戏后端分布式学习——消息队列在游戏的用法
  • 伪类选择器
  • Linux蓝牙管理神器Blueman:3分钟搞定无线设备连接
  • 常用的激活函数总结
  • 灌装机品牌哪家好?2026年市场深度评测与选购指南 - 品牌推荐
  • Tg分级差异带来板材成本波动,采购议价与预算管控策略
  • 计算机毕业设计之《计算机网络》在线学习平台设计与实现
  • Linux用户、群组与权限
  • 为什么要使用元组tuple?
  • 双拐撑起的从容 - 东方既白~(-^