尧图网站建设 尧图网络
  • 首页
  • 关于我们
  • 服务项目
  • 案例展示
  • 建站流程
  • 资讯中心
  • 联系我们
首页/资讯中心/详情

Netty(一)之helloworld

Netty(一)之helloworld
📅 发布时间:2026/7/28 18:35:21

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)请坚持

相关新闻

  • 终极鼠标优化方案:让你的普通鼠标在macOS上超越苹果触控板体验
  • NLTK获取停用词
  • 版本的比较(java)

最新新闻

  • iptables/nftables 防火墙实战:从入门到企业规则集
  • 山东非标自动化设备厂家哪家好?2026避坑指南:4个坑+5条硬标准,帮你选对靠谱服务商 - GEO99
  • 别信社交媒体谣言:94%的电动车车主不会回归燃油车
  • Windows 11任务栏歌词显示终极指南:让音乐伴随你的工作流程
  • 进口二手机床验机避坑:主轴精度与激光干涉仪检测全流程
  • PAT甲级 1063 Set Similarity set集合的使用

日新闻

  • 力旷智能:伺服驱动系统在制药收瓶设备中的应用解析
  • 2026 网安入门避坑指南,零基础如何避开无效学习直接上手实战
  • 揭秘CFC项目:如何通过手机摄像头实现850kbps无网络文件传输

周新闻

  • 大连理工大学与东京大学联手打造的“主动型AI助手“
  • 170.2026年国家级科研瓶颈:超精密单点金刚石切削(SPDT)光学表面生成
  • SongBloom:革命性歌曲生成框架深度解析——如何通过交织自回归与扩散模型创作完整音乐

月新闻

  • 2026年6月公司网站搭建最新热门渠道测评:四大低成本/零代码平台对比+避坑
  • 【Linux】Linux arm 编译QT程序,出现expected “}“报错
  • 【MATLAB例程】四基站二维AOA定位与距离辅助增强对比仿真。基于角度观测和测距修正的固定目标平面定位精度分析

关于尧图

  • 公司简介
  • 团队介绍
  • 企业文化
  • 荣誉资质

服务项目

  • 定制开发
  • 电商建站
  • UI 设计
  • 运维服务

快速链接

  • 案例展示
  • 建站流程
  • 常见问题
  • 资讯中心

联系方式

  • 📍北京市朝阳区互联网产业园 A 座 10 层
  • 📞400-888-8888
  • ✉️contact@rkmt.cn
  • 🕐周一至周日 9:00-21:00

© 2024 北京尧图网络科技有限公司 版权所有 | 京 ICP 备 XXXXXXXX 号