netty转发tcp连接

Netty 是一个高性能的网络应用框架,常用于构建高性能的 TCP/UDP 服务器和客户端。如果您想使用 Netty 转发 TCP 连接,可以创建一个简单的 TCP 代理(或中间人),它接收来自客户端的连接,然后将这些连接转发到目标服务器。

以下是一个简单的例子,演示如何使用 Netty 实现 TCP 连接的转发。

import io.netty.bootstrap.ServerBootstrap;
import io.netty.bootstrap.Bootstrap;
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.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class TcpForwardingServer {

    private final int localPort;
    private final String remoteHost;
    private final int remotePort;

    public TcpForwardingServer(int localPort, String remoteHost, int remotePort) {
        this.localPort = localPort;
        this.remoteHost = remoteHost;
        this.remotePort = remotePort;
    }

    public void start() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // 启动服务器
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new TcpForwardHandler(remoteHost, remotePort));
                        }
                    });

            ChannelFuture serverFuture = serverBootstrap.bind(localPort).sync();
            System.out.println("TCP Forwarding Server started on port " + localPort);

            serverFuture.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int localPort = 9991; // 本地监听端口
        String remoteHost = "127.0.0.1"; // 目标服务器地址
        int remotePort = 9091; // 目标服务器端口

        new TcpForwardingServer(localPort, remoteHost, remotePort).start();
    }
}

class TcpForwardHandler extends ChannelInboundHandlerAdapter {
    private final String remoteHost;
    private final int remotePort;
    private ChannelFuture remoteChannelFuture;

    public TcpForwardHandler(String remoteHost, int remotePort) {
        this.remoteHost = remoteHost;
        this.remotePort = remotePort;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 连接到远程主机
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(ctx.channel().eventLoop())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new TcpForwardClientHandler(ctx));
                    }
                });

        remoteChannelFuture = bootstrap.connect(remoteHost, remotePort);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

class TcpForwardClientHandler extends ChannelInboundHandlerAdapter {
    private final ChannelHandlerContext clientCtx;

    public TcpForwardClientHandler(ChannelHandlerContext clientCtx) {
        this.clientCtx = clientCtx;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 将接收到的数据转发到客户端
        clientCtx.writeAndFlush(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

代码说明

1. TcpForwardingServer:
   - 这个类负责启动 TCP 服务器,监听来自客户端的连接请求,并将其转发到指定的远程服务器。

2. TcpForwardHandler:
   - 当客户端连接到转发服务器时,`channelActive` 方法会被调用。在这个方法中,它会连接到目标服务器。
   - 该处理程序会监听来自客户端的流量,并将其转发到目标服务器。

3. TcpForwardClientHandler:
   - 这个类处理从远程服务器接收到的数据,并将其转发回原始客户端。

运行方式

1. **编译并运行**:
   - 确保您已经在项目中添加了 Netty 依赖。如果使用 Maven,可以在 `pom.xml` 中添加以下依赖:

     <dependency>
         <groupId>io.netty</groupId>
         <artifactId>netty-all</artifactId>
         <version>4.1.68.Final</version> <!-- 使用最新版本 -->
     </dependency>

2. 配置参数:
   - 在 `main` 方法中,您可以根据需要更改 `localPort`、`remoteHost` 和 `remotePort` 变量。

3. 启动服务器:
   - 运行程序后,您的 TCP 代理服务器将开始监听指定的本地端口,并将其流量转发到目标服务器。

总结

使用 Netty 转发 TCP 连接是非常灵活和高效的。通过自定义处理程序,您可以根据需要实现复杂的逻辑。上述示例是一个基本的实现,可以根据具体需求进行调整和增强。

  • 8
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

憨子周

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值