Netty(一)之helloworld
HelloWorld客户端通向服务器端发送消息服务器端读取数据你好并且返回new Date()客户端读取数据pomdependency groupIdio.netty/groupId artifactIdnetty-all/artifactId version5.0.0.Alpha1/version /dependencyTimeServerHandler服务器端读取数据并且回应请求继承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(); } // }TimeServerpackage 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 ChannelInitializerSocketChannel() { 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(); } }TimeClientpackage 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 ChannelInitializerSocketChannel() { 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.1option(ChannelOption.SO_BACKLOG, 1024) 修改一些参数2.2socketChannel.pipeline().addLast(new TimeServerHandler())添加一些自己定义或者系统的handler2.3自己定义的handler3请坚持

相关新闻

终极指南:如何免费解锁WeMod完整功能,获得专业版体验

终极指南:如何免费解锁WeMod完整功能,获得专业版体验

终极指南:如何免费解锁WeMod完整功能,获得专业版体验 【免费下载链接】Wand-Enhancer Advanced UX and interoperability extension for Wand (WeMod) app 项目地址: https://gitcode.com/GitHub_Trending/we/Wand-Enhancer 还在为WeMod专业版功能…

2026/9/28 10:45:43 阅读更多 →
Playwright自定义Fixtures:解决测试数据管理与环境隔离的工程实践

Playwright自定义Fixtures:解决测试数据管理与环境隔离的工程实践

1. 项目概述:为什么我们需要自定义 Fixtures?如果你在用 Playwright 做自动化测试,大概率已经熟悉了它的test函数和page对象。官方提供的test和page这些内置 Fixtures 确实方便,开箱即用。但当你开始构建一个稍具规模的测试套件时…

2026/9/28 1:59:26 阅读更多 →
Ryujinx模拟器终极指南:3步在PC上畅玩Switch游戏

Ryujinx模拟器终极指南:3步在PC上畅玩Switch游戏

Ryujinx模拟器终极指南:3步在PC上畅玩Switch游戏 【免费下载链接】Ryujinx 用 C# 编写的实验性 Nintendo Switch 模拟器 项目地址: https://gitcode.com/GitHub_Trending/ry/Ryujinx 想在电脑上体验Switch独占大作却不知从何入手?Ryujinx模拟器为…

2026/9/26 2:31:10 阅读更多 →

最新新闻

从CANoe到TSMaster:车载总线测试工具链迁移实战指南

从CANoe到TSMaster:车载总线测试工具链迁移实战指南

搞车载总线测试的工程师,电脑里大概率都装着一套CANoe。我最早接触CANoe是刚入行那会儿,跟着前辈在项目里做网络测试,从报文发送、DBC解析到UDS诊断,基本全是靠Vector这套工具撑起来的。说实话,CANoe确实是这个行业的标…

2026/9/28 9:43:09 阅读更多 →
从刷榜到用榜:GitHub Trending 的增量逻辑、项目筛选与高效落地

从刷榜到用榜:GitHub Trending 的增量逻辑、项目筛选与高效落地

1. 日榜的"热度"到底是怎么算出来的先别急着收藏仓库。每天打开 GitHub 的 Trending 页面,你看到的是过去 24 小时内 Star 增量最高的仓库,周榜和月榜则分别看一周、一个月内的增量。官方没有公开完整排序算法,但用久了会发现&…

2026/9/28 9:43:09 阅读更多 →
【Java开发MCP】SSE模式开发并集成MCP:TaoToken统一Key接入与SpringAI WebFlux配置骨架

【Java开发MCP】SSE模式开发并集成MCP:TaoToken统一Key接入与SpringAI WebFlux配置骨架

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/9/28 9:43:09 阅读更多 →
OpenCompass 高效评测:Partitioner 任务切分与 Runner 执行后端实战指南

OpenCompass 高效评测:Partitioner 任务切分与 Runner 执行后端实战指南

模型评测人工智能大模型AI 评测 【免费下载链接】opencompass OpenCompass is an LLM evaluation platform, supporting a wide range of models from OpenAI, Anthropic, Gemini, Qwen, GLM, DeepSeek, etc, across 100 datasets covering knowledge, reasoning, coding, scie…

2026/9/28 9:43:09 阅读更多 →
快速搭建网站的工具怎么选?3个方案省下5万冤枉钱

快速搭建网站的工具怎么选?3个方案省下5万冤枉钱

快速搭建网站的工具怎么选?3个方案省下5万冤枉钱 网站做好了没人访问,这是很多老板最头疼的事。你花大价钱做的官网,设计精美、功能齐全,但打开一看,流量为零,咨询为零。这时候你才意识到,问题不在“做没做”,而在“怎么快速做出来并推向市场”。面…

2026/9/28 9:43:09 阅读更多 →
YOLOv5车辆检测实战:从car_dataset-1到树莓派部署

YOLOv5车辆检测实战:从car_dataset-1到树莓派部署

简介:本资源是一个专为车辆目标检测任务构建的高质量标注数据集,适用于YOLOv5、YOLOv3及SSD等主流检测模型的训练与验证,面向计算机视觉初学者、算法工程师及智能交通项目开发者,有效解决夜间、白天及俯视视角下车辆识别的数据匮乏…

2026/9/28 9:42:00 阅读更多 →

日新闻

济南做网站多少钱:3个案例拆解,防黑源码下载全攻略

济南做网站多少钱:3个案例拆解,防黑源码下载全攻略

济南做网站多少钱:3个案例拆解,防黑源码下载全攻略 上周济南一个做建材的老板找我,脸都绿了。他的官网首页弹出了赌博广告,后台被植入了挖矿脚本。他慌得问我:“网站被黑挂马不知道怎么办?能不能直接找之前的外包公司要源码下载,看看哪里被动了手脚?…

2026/9/28 0:00:34 阅读更多 →
婚恋网站实战案例:避开3个高价坑,省钱50%还能跑赢流量

婚恋网站实战案例:避开3个高价坑,省钱50%还能跑赢流量

婚恋网站实战案例:避开3个高价坑,省钱50%还能跑赢流量 找婚恋网站建站公司,最怕的就是被坑高价。很多同行跟我吐槽,报价单上写得模棱两可,功能栏里全是“高级定制”、“专属UI”,结果落地全是套壳。今天不聊虚的,直接甩几个我经手的 实战案例…

2026/9/28 0:00:34 阅读更多 →
制作网页比较方便的软件怎么选?一文搞懂避坑指南

制作网页比较方便的软件怎么选?一文搞懂避坑指南

制作网页比较方便的软件怎么选?一文搞懂避坑指南 很多老板一上来就问:做个网站多少钱?但我反问他:你的域名买了吗?服务器租了吗?他一脸懵。这就是典型的“域名服务器搞不懂”。别急,今天咱们不聊虚的,直接 一文搞懂 那些让你头秃的技术名词。…

2026/9/28 0:00:34 阅读更多 →

周新闻

如何划分训练/验证集:Spirula Studio五种eval_mode策略详解

如何划分训练/验证集:Spirula Studio五种eval_mode策略详解

如何划分训练/验证集:Spirula Studio五种eval_mode策略详解 【免费下载链接】spirula-studio Cross-vendor 3D Gaussian Splatting trainer - video to splat to mesh, Vulkan or CUDA. 项目地址: https://gitcode.com/GitHub_Trending/sp/spirula-studio Sp…

2026/9/28 5:40:26 阅读更多 →
SEO怎么推广速查手册新手避坑实战指南

SEO怎么推广速查手册新手避坑实战指南

SEO怎么推广速查手册新手避坑实战指南 模板网站太丑不够用?别急着加滤镜,那是治标不治本。很多老板盯着后台流量掉得眼红,却还在纠结首页Banner的圆角是不是3像素。这就像穿着西装去挖土,姿势不对,努力白费。我整理这份 速查手册…

2026/9/28 9:47:26 阅读更多 →
FireRed-OpenStoryline少样本仿写深度解析:AI Agent如何复刻你的独特文案风格与节奏

FireRed-OpenStoryline少样本仿写深度解析:AI Agent如何复刻你的独特文案风格与节奏

FireRed-OpenStoryline少样本仿写深度解析:AI Agent如何复刻你的独特文案风格与节奏 【免费下载链接】FireRed-OpenStoryline FireRed-OpenStoryline is an AI video editing agent that transforms manual editing into intention-driven directing through natural language …

2026/9/28 8:07:01 阅读更多 →

月新闻

持续集成 流水线自动化与 声明式交付 实践:原型怎样变成可用功能

持续集成 流水线自动化与 声明式交付 实践:原型怎样变成可用功能

持续集成 流水线自动化与 声明式交付 实践:原型怎样变成可用功能分类:[AI/大模型]细分主题:AI 增强型 CI/CD 流水线自动化与 GitOps 实践:Agent 工作流、工具调用与任务拆解:从原型到生产的验收清单很多团队在尝试用大…

2026/9/27 9:12:14 阅读更多 →
容器编排 生产环境运维与排障实战:复盘记录怎样真正派上用场

容器编排 生产环境运维与排障实战:复盘记录怎样真正派上用场

容器编排 生产环境运维与排障实战:复盘记录怎样真正派上用场分类:[工程技术]细分主题:Kubernetes 生产环境运维与排障实战:可复制的项目复盘模板与决策记录大部分团队的事故复盘报告,最后都变成了躺在 Confluence 或钉…

2026/9/28 3:51:11 阅读更多 →
容器 容器化技术与镜像安全管理:核心链路应该先拆哪一步

容器 容器化技术与镜像安全管理:核心链路应该先拆哪一步

容器 容器化技术与镜像安全管理:核心链路应该先拆哪一步分类:[工程技术]细分主题:Docker 容器化技术与镜像安全管理:核心链路的逐步实现与关键代码取舍面对一个积累了五六年历史包袱的单体架构应用(包含 Web 接口、后台…

2026/9/26 22:52:30 阅读更多 →