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

Netty入门案例:简单Echo服务器(同步)

目录

1、添加 Netty 依赖

2、服务器端

3、客户端

4、运行步骤


1、添加 Netty 依赖

<dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>4.1.68.Final</version> <!-- 使用最新版本 -->
</dependency>

2、服务器端

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;public class EchoServer {private final int port;public EchoServer(int port) {this.port = port;}public void start() throws Exception {// 1、创建bossGroup线程组,处理连接请求,线程数默认:2*处理器线程数EventLoopGroup bossGroup = new NioEventLoopGroup(); // 2、创建workerGroup线程组,处理业务(读写事件),线程数默认:2*处理器线程数EventLoopGroup workerGroup = new NioEventLoopGroup(); try {// 3、创建服务端启动助手ServerBootstrap b = new ServerBootstrap();// 4、设置线程组b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // 5、设置服务端通道实现,使用NIO传输.option(ChannelOption.SO_BACKLOG, 128) // 6、设置连接队列大小.childOption(ChannelOption.SO_KEEPALIVE, true); // 7、保持长连接.childHandler(new ChannelInitializer<SocketChannel>() {// 8、创建一个通道初始化对象@Overridepublic void initChannel(SocketChannel ch) throws Exception {// 9、向pipeline中添加自定义业务处理handlerch.pipeline().addLast(new EchoServerHandler());}})// 10、绑定端口并开始接收连接,同时将异步改为同步ChannelFuture f = b.bind(port).sync();System.out.println("EchoServer started and listen on " + f.channel().localAddress());// 11、等待服务器socket关闭f.channel().closeFuture().sync();} finally {// 12、关闭通道和连接池workerGroup.shutdownGracefully();bossGroup.shutdownGracefully();}}public static void main(String[] args) throws Exception {int port = 8080;new EchoServer(port).start();}
}

服务器端处理器:

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;public class EchoServerHandler extends ChannelInboundHandlerAdapter {/*** 通道读取事件** @param ctx 通道上下文对象* @param msg 消息* @throws Exception*/@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) {ByteBuf in = (ByteBuf) msg;System.out.println("Server received: " + in.toString(io.netty.util.CharsetUtil.UTF_8));ctx.write(in); // 将接收到的消息回写给发送者,而不冲刷出站消息}/*** 读取完毕事件** @param ctx* @throws Exception*/@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) {//ctx.writeAndFlush(Unpooled.copiedBuffer("你好,我是Netty服务端.", CharsetUtil.UTF_8));ctx.flush(); // 将未决消息冲刷到远程节点,并关闭该Channel}/*** 异常发生事件** @param ctx* @param cause* @throws Exception*/@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {cause.printStackTrace();ctx.close(); // 关闭该Channel}
}

3、客户端

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;public class EchoClient {private final String host;private final int port;public EchoClient(String host, int port) {this.host = host;this.port = port;}public void start() throws Exception {// 1、创建线程组EventLoopGroup group = new NioEventLoopGroup();try {// 2、创建客户端启动助手Bootstrap b = new Bootstrap();// 3、设置线程组b.group(group).channel(NioSocketChannel.class) //4、设置服务端通道实现为NIO.handler(new ChannelInitializer<SocketChannel>() { //5、创建一个通道初始化对象@Overridepublic void initChannel(SocketChannel ch) throws Exception {//6、向pipeline中添加自定义业务处理handlerch.pipeline().addLast(new EchoClientHandler());}});// 7、连接到服务器,将异步改为同步ChannelFuture f = b.connect(host, port).sync();System.out.println("Connected to server");// 8、发送消息String message = "Hello, Netty!";ByteBuf buf = Unpooled.copiedBuffer(message.getBytes());f.channel().writeAndFlush(buf);// 9、等待连接关闭f.channel().closeFuture().sync();} finally {// 10、关闭连接池group.shutdownGracefully();}}public static void main(String[] args) throws Exception {new EchoClient("localhost", 8080).start();}
}

客户端处理器:

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;public class EchoClientHandler extends ChannelInboundHandlerAdapter {/*** 通道就绪事件** @param ctx* @throws Exception*/@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {ctx.writeAndFlush(Unpooled.copiedBuffer("你好呀,我是Netty客户端", CharsetUtil.UTF_8));}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) {ByteBuf in = (ByteBuf) msg;System.out.println("Client received: " + in.toString(io.netty.util.CharsetUtil.UTF_8));}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {cause.printStackTrace();ctx.close();}
}

4、运行步骤

  1. 首先启动 EchoServer,它将监听 8080 端口

  2. 然后启动 EchoClient,它将连接到服务器并发送一条消息

  3. 服务器会将接收到的消息回传给客户端

  4. 将在客户端控制台看到服务器返回的消息

http://www.lqws.cn/news/540595.html

相关文章:

  • 航天VR赋能,无人机总测实验舱开启高效新篇​
  • 探秘 VR 逃生救援技术的奇妙世界​
  • 自动化保护 AWS ECS Fargate 服务:使用 Prisma Cloud 实现容器安全
  • Linux工作常用命令记录
  • 系统学习 Android 的 进程管理、内存管理、音频管理
  • 【人工智能与机器人研究】基于改进长短焦图像融合技术的轨道交通障碍物检测系统研究
  • 飞凌A40i使用笔记
  • 【RAG面试题】LLMs已经具备了较强能力,存在哪些不足点?
  • 命名数据网络 | 签名(Signature)
  • 电力微气象在线监测系统:温湿度 / 风速 / 气压多要素监测
  • ROS:录制相机、IMU、GNSS等设备数据
  • AI+实时计算如何赋能金融系统?DolphinDB 在国泰君安期货年度中期策略会的演讲
  • JetBrains AI助手登陆Android Studio!智能编码提升Kotlin开发效能
  • AI+物联网:从万物互联到万物智联
  • Spring 框架中@Resource和@Autowired是用于实现依赖注入的两个重要注解,及@Primary注解
  • 代码随想录|图论|09沉没孤岛
  • vue项目中纯前端实现导出pdf文件,不需要后端处理。
  • 论基于架构的软件设计方法(ABSD)及应用
  • Ehcache、Caffeine、Spring Cache、Redis、J2Cache、Memcached 和 Guava Cache 的主要区别
  • 【ubuntu24.04】忘了自己把开机samba挂载的脚本放哪里了
  • 【C++特殊工具与技术】固有的不可移植的特性(3)::extern“C“
  • Python实例题:文件内容搜索工具
  • 学习记录:DAY34
  • 树的重心(双dfs,换根)
  • 目标跟踪存在问题以及解决方案
  • 算法第54天| 并查集
  • 【Redis】解码Redis中的list类型,基本命令,内部编码方式以及适用的场景
  • 分布式ID生成SnowflakeId雪花算法和百度UidGenerator工具类
  • 深入解析:Vue 中的 Render 函数、JSX 与 @vitejs/plugin-vue-jsx 实践指南
  • DeepSeek 部署中的常见问题及解决方案:从环境配置到性能优化的全流程指南