博客
关于我
netty--helloword程序
阅读量:790 次
发布时间:2023-02-14

本文共 3451 字,大约阅读时间需要 11 分钟。

Netty编程实践指南

1. Netty的基本使用

Netty是一款流行的异步I/O框架,适用于高性能网络应用开发。以下是使用Netty的基本步骤:

1.1 必要 jars

  • netty-all-5.0.0.Alpha2.jar
  • 其他依赖包(如具体业务需求)

1.2 代码示例

服务端代码

package bhz.netty.test;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;public class Server {    public static void main(String[] args) throws Exception {        // 1. 创建事件循环组        EventLoopGroup bossGroup = new NioEventLoopGroup();        EventLoopGroup workerGroup = new NioEventLoopGroup();        // 2. 创建Bootstrap实例        ServerBootstrap b = new ServerBootstrap();        // 3. 配置通道        b.channel(NioServerSocketChannel.class)                .group(bossGroup, workerGroup)                .childHandler(new ChannelInitializer
() { @Override protected void initChannel(SocketChannel sc) throws Exception { sc.pipeline().addLast(new ServerHandler()); } }); // 4. 绑定端口并启动服务器 ChannelFuture f = b.bind(8765).sync(); f.channel().closeFuture().sync(); // 关闭资源 bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); }}

客户端代码

package bhz.netty.test;import io.netty.bootstrap.Bootstrap;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelInitializer;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioSocketChannel;public class Client {    public static void main(String[] args) throws Exception {        // 1. 创建事件循环组        EventLoopGroup workGroup = new NioEventLoopGroup();        // 2. 创建Bootstrap实例        Bootstrap b = new Bootstrap();        // 3. 配置通道        b.channel(NioSocketChannel.class)                .group(workGroup)                .handler(new ChannelInitializer
() { @Override protected void initChannel(SocketChannel sc) throws Exception { sc.pipeline().addLast(new ClientHandler()); } }); // 4. 连接服务器 ChannelFuture cf = b.connect("127.0.0.1", 8765).sync(); cf.channel().closeFuture().sync(); // 关闭资源 workGroup.shutdownGracefully(); }}

2. 注意事项

2.1 数据发送问题

在客户端多次调用write方法时,若最后未调用flush,服务器端只会接收一次完整的数据。建议使用writeAndFlush方法以确保数据及时发送。

2.2 数据回复处理

服务端接收客户端数据后,应及时回复。可以通过添加监听器来检测客户端是否接收到数据,从而决定是否关闭连接。

2.3 优化代码

服务端的ServerHandler可以简化为以下形式:

public class ServerHandler extends ChannelHandlerAdapter {    @Override    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {        try {            ByteBuf buf = (ByteBuf) msg;            byte[] data = new byte[buf.readableBytes()];            buf.readBytes(data);            String request = new String(data, "utf-8");            System.out.println("Server: " + request);            // 发回响应            ctx.writeAndFlush(Unpooled.copiedBuffer("888".getBytes()));        } finally {            ReferenceCountUtil.release(msg);        }    }}

3. 总结

Netty是一个强大的异步I/O框架,适用于高性能网络应用开发。通过合理配置和优化代码,可以实现高效的数据传输和处理。记得在实际应用中注意线程资源的管理和异常处理,以确保程序的稳定性和可靠性。

转载自:原文链接

你可能感兴趣的文章
mysql进阶 with-as 性能调优
查看>>
mysql进阶-查询优化-慢查询日志
查看>>
wargame narnia writeup
查看>>
MySQL进阶篇SQL优化(InnoDB锁问题排查与解决)
查看>>
Mysql进阶索引篇03——2个新特性,11+7条设计原则教你创建索引
查看>>
Mysql连接时报时区错误
查看>>
mysql逗号分隔的字符串如何搜索
查看>>
MYSQL遇到Deadlock found when trying to get lock,解决方案
查看>>
MYSQL遇到Deadlock found when trying to get lock,解决方案
查看>>
mysql部署错误
查看>>
MySQL配置信息解读(my.cnf)
查看>>
Mysql配置文件my.ini详解
查看>>
MySQL配置文件深度解析:10个关键参数及优化技巧---强烈要求的福利来咯。
查看>>
Mysql配置表名忽略大小写(SpringBoot连接表时提示不存在,实际是存在的)
查看>>
mysql配置读写分离并在若依框架使用读写分离
查看>>
MySQL里为什么会建议不要使用SELECT *?
查看>>
MySQL里的那些日志们
查看>>
MySQL锁
查看>>
MySQL锁与脏读、不可重复读、幻读详解
查看>>
MySQL锁机制
查看>>