Netty(7)如何实现基于Netty的TCP客户端和服务器?

要实现基于Netty的TCP客户端和服务器,您需要编写以下代码来设置和配置客户端和服务器:

  1. 创建服务器:
java 复制代码
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;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class TcpServer {
    private final int port;

    public TcpServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringDecoder(), new StringEncoder(), new ServerHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        TcpServer server = new TcpServer(port);
        server.run();
    }
}

在上面的示例中,我们创建了一个TcpServer类,它负责启动服务器。在run()方法中,我们使用NioEventLoopGroup创建了两个EventLoopGroup,一个用于接受客户端连接(bossGroup),另一个用于处理客户端连接的I/O操作(workerGroup)。

然后,我们使用ServerBootstrap来配置服务器。我们指定了服务器的通道类型为NioServerSocketChannel,设置了服务器的处理器(ChannelInitializer)为StringDecoder、StringEncoder和ServerHandler。

最后,我们绑定服务器的端口并启动服务器。

  1. 创建客户端:
java 复制代码
import io.netty.bootstrap.Bootstrap;
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;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class TcpClient {
    private final String host;
    private final int port;

    public TcpClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringDecoder(), new StringEncoder(), new ClientHandler());
                        }
                    })
                    .option(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = b.connect(host, port).sync();
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        String host = "localhost";
        int port = 8080;
        TcpClient client = new TcpClient(host, port);
        client.run();
    }
}

在上面的示例中,我们创建了一个TcpClient类,它负责启动客户端。在run()方法中,我们使用NioEventLoopGroup创建了一个EventLoopGroup,用于处理客户端的I/O操作。

然后,我们使用Bootstrap来配置客户端。我们指定了客户端的通道类型为NioSocketChannel,设置了客户端的处理器(ChannelInitializer)为StringDecoder、StringEncoder和ClientHandler。

最后,我们连接服务器的主机和端口,并启动客户端。

需要注意的是,上述代码中的ServerHandler和ClientHandler是自定义的处理器,您可以根据自己的需求实现相应的处理逻辑。

相关推荐
Knight_AL几秒前
使用 Nginx 为内网 Java 服务实现 HTTPS
java·nginx·https
提笔忘字的帝国2 分钟前
【2026版】macOS 使用 Homebrew 快速安装 Java 21 教程
java·开发语言·macos
2501_915918414 分钟前
iOS App的tcp、udp数据包抓取在实际开发中的使用方式
android·tcp/ip·ios·小程序·udp·uni-app·iphone
上海云盾安全满满5 分钟前
高防IP加速作用
网络·tcp/ip·安全
抹香鲸之海7 分钟前
Easyexcel 多级横向合并表头
java·开发语言·windows
阿巴~阿巴~8 分钟前
深入解析IP分片:从原理到现代实践的全面指南
运维·服务器·网络·网络协议·tcp/ip·ip
烟沙九洲11 分钟前
JVM 堆内存分代
java·jvm
BD_Marathon11 分钟前
SpringMVC——bean加载控制
java·开发语言·数据库
阿巴~阿巴~17 分钟前
IPv4地址的边界与智慧:特殊用途、枯竭挑战与应对策略全景解析
运维·服务器·网络·网络协议·tcp/ip·ipv4·ipv4地址枯竭
悟空码字17 分钟前
SpringBoot + Redis分布式锁深度剖析,性能暴涨的秘密全在这里
java·spring boot·后端