当前位置: 首页 > 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. 将在客户端控制台看到服务器返回的消息

相关文章:

  • 【Linux高级全栈开发】2.2.3 UDP的可靠传输协议QUIC
  • 路径遍历攻击与修复
  • 非功能测试
  • 【论文阅读 | CVPR 2025 |MambaVision:一种混合 Mamba-Transformer 视觉骨干网络】
  • 【Android】蓝牙相关
  • 基于大模型的肺结核诊疗全流程预测与干预研究报告
  • 什么是国际期货?期货交易平台搭建
  • debian挂载新硬盘后不识别怎么办?
  • 将ONNX模型转换为(OPENMV可用的格式)TensorFlow Lite格式
  • Elasticsearch(ES)分页
  • 预训练语言模型
  • 使用Puppeteer提取页面内容的技巧
  • 航拍图像中的“生命线”:基于YOLOv5的7类应急目标检测实践
  • 电力物联网简介
  • Datasophon1.2.1安装HDFS开启Kerberos
  • java+vue+SpringBoo海鲜市场系统(程序+数据库+报告+部署教程+答辩指导)
  • 【MySQL进阶】服务器配置与管理——系统变量,选项,状态变量
  • 为什么在linux中不能直接使用pip进行安装
  • MySQL(1)——count()聚合函数
  • 【记录】Ubuntu|Ubuntu服务器挂载新的硬盘的流程(开机自动挂载)