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

相关推荐
Victor3562 小时前
Netty(8)什么是Netty的ChannelPipeline和ChannelHandler?
后端
乘风!3 小时前
NSSM启动tomcat部署Java程序
java·服务器·后端·tomcat
代码无疆4 小时前
学点java字节码更易于理解一些特殊的java语法效果
java·后端
星浩AI4 小时前
AI 并不懂文字,它只认向量:一文搞懂 Embedding
后端
程序员博博4 小时前
这才是vibe coding正确的打开方式 - 手把手教你开发一个MCP服务
javascript·人工智能·后端
90后的晨仔4 小时前
阿里云服务器如何给子账号设置指定具体的那一台服务器?
后端
期待のcode5 小时前
springboot热部署
java·spring boot·后端
expect7g5 小时前
Paimon源码解读 -- FULL_COMPACTION_DELTA_COMMITS
大数据·后端·flink
踏浪无痕5 小时前
周末拆解:QLExpress 如何做到不编译就能执行?
后端·算法·架构