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/10/22 9:14:27 阅读更多 →
Playwright自定义Fixtures:解决测试数据管理与环境隔离的工程实践

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

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

2026/11/4 1:55:15 阅读更多 →
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/10/30 22:40:29 阅读更多 →

最新新闻

Electron桌面应用开发实战:从环境搭建到打包发布全流程

Electron桌面应用开发实战:从环境搭建到打包发布全流程

做前端这些年,我大部分时间都在跟浏览器标签页打交道,直到第一次把桌面应用跑起来,才发现原来自己一直被限制在地址栏和刷新按钮围起来的框框里。Electron这个词,最开始是在某段时间频繁出现在同事的讨论里,一个用HTML…

2026/11/4 1:35:24 阅读更多 →
滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

简介:亚太天能T109滑盖智能锁产品说明书是一份PDF格式的官方技术文档,主要面向智能锁安装人员、终端用户及售后维护者,帮助快速掌握产品安装、配置与常见故障处理。全包仅1个PDF文件,大小4.37MB,内容结构清晰&#xff…

2026/11/3 10:57:27 阅读更多 →
PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

上个月我在调试一台高速AGV的驱动系统,整车要求空载跑到8m/s,电机转速已经拉到额定点,驱动器的输出电压也顶到了母线电压极限附近。再往上踩速度指令,转速纹丝不动,三相电流反而开始震荡。那会儿我的第一反应就是&…

2026/11/3 11:35:49 阅读更多 →
C++核心知识点:从内存管理到STL的实战指南

C++核心知识点:从内存管理到STL的实战指南

C 这门语言我前前后后折腾了十几年,用它写过嵌入式驱动、做过游戏服务端,也搭过基础组件库。每次看到新人一头扎进"C 核心知识点"这个搜索词,我其实挺感慨的——这门语言的难点从来不是语法多,而是知识点之间的耦合太深…

2026/11/4 6:23:50 阅读更多 →
T109滑盖智能锁怎么装?安装调试与故障排查全攻略

T109滑盖智能锁怎么装?安装调试与故障排查全攻略

简介:亚太天能T109滑盖智能锁产品说明书以PDF格式发布,适合智能锁用户、安装人员与售后维修人员阅读。内容围绕T109系列指纹密码刷卡锁展开,先介绍前面板、后面板、锁体、机械钥匙、电池盒盖等部件名称与功能,再给出完整安装步骤&…

2026/11/3 10:47:27 阅读更多 →
LLM知识降熵:从信息垄断到理解权下放

LLM知识降熵:从信息垄断到理解权下放

你有没有过这种经历:翻开源码注释、论文摘要或者一份专业报告,每个字都认识,连在一起却像天书。想找人聊聊,身边要么没人懂,要么懂的懒得跟你解释。后来我试着把同一段内容丢给一个大语言模型,几秒钟之后&a…

2026/11/3 10:57:33 阅读更多 →

日新闻

周新闻

月新闻