本文共 3451 字,大约阅读时间需要 11 分钟。
Netty是一款流行的异步I/O框架,适用于高性能网络应用开发。以下是使用Netty的基本步骤:
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(); }} 在客户端多次调用write方法时,若最后未调用flush,服务器端只会接收一次完整的数据。建议使用writeAndFlush方法以确保数据及时发送。
服务端接收客户端数据后,应及时回复。可以通过添加监听器来检测客户端是否接收到数据,从而决定是否关闭连接。
服务端的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); } }} Netty是一个强大的异步I/O框架,适用于高性能网络应用开发。通过合理配置和优化代码,可以实现高效的数据传输和处理。记得在实际应用中注意线程资源的管理和异常处理,以确保程序的稳定性和可靠性。
转载自:原文链接