下面是一个简单的Netty TCP客户端代码示例:

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

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 start() throws Exception {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new TcpClientHandler());
                        }
                    });

            ChannelFuture future = bootstrap.connect(host, port).sync();
            future.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.start();
    }

    private static class TcpClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            // 当连接建立时发送数据
            byte[] data = "Hello, server!".getBytes();
            ByteBuf buf = Unpooled.buffer(data.length);
            buf.writeBytes(data);
            ctx.writeAndFlush(buf);
        }

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
            // 接收到服务器的响应
            byte[] data = new byte[msg.readableBytes()];
            msg.readBytes(data);
            System.out.println("Received: " + new String(data));
            ctx.close();
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            // 发生异常时关闭连接
            cause.printStackTrace();
            ctx.close();
        }
    }
}

以上代码创建了一个简单的Netty TCP客户端,它通过TCP连接到指定的主机和端口,然后发送一条消息给服务器,并接收服务器的响应。在TcpClientHandler类中,我们重写了channelActive方法,在连接建立时发送数据,重写了channelRead0方法,在接收到服务器的响应时处理数据,重写了exceptionCaught方法,在发生异常时关闭连接。

要运行这个示例,你需要添加Netty的依赖,例如:

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.65.Final</version>
</dependency>

请确保将hostport变量设置为你要连接的服务器的主机和端口。

Netty tcp client 代码

原文地址: https://www.cveoy.top/t/topic/i4gw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录