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是自定义的处理器,您可以根据自己的需求实现相应的处理逻辑。

相关推荐
牛奶咖啡134 小时前
Linux系统故障排查思路实践教程(上)
linux·服务器·linux系统故障排查思路·linux的日志分类与分析·忘记linux用户密码问题解决·系统无法启动问题解决·linux文件系统只读问题解决
全栈独立开发者4 小时前
软考架构师实战:Spring Boot 3.5 + DeepSeek 开发 AI 应用,上线 24 小时数据复盘(2C1G 服务器抗压实录)
java·spring boot·后端
CoderYanger4 小时前
D.二分查找-基础-2529. 正整数和负整数的最大计数
java·开发语言·数据结构·算法·leetcode·职场和发展
想唱rap4 小时前
Linux下进程的控制
linux·运维·服务器·c++·算法
小光学长4 小时前
ssm农民养殖经验交流与分享平台bc046578(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
java·数据库·spring
E***U9454 小时前
Java 校招 / 社招:Spring Boot 项目实战指南
java·开发语言·spring boot
在坚持一下我可没意见4 小时前
Spring 开发小白学习过程中常用通用配置文件,即拿即用!(持续更新中)
java·数据库·后端·学习·spring·tomcat·mybatis
一叶之秋14124 小时前
QT常用控件(一)
服务器·开发语言·qt
极地星光4 小时前
Asio网络编程入门:从零构建同步客户端与服务器
服务器·网络