在channelhandler中连接到netty中的客户端

时间:2017-05-19 20:06:20

标签: java netty

我正在尝试从我在Netty中构建的服务器连接到另一个客户端。我在这里查看了代理示例:http://netty.io/4.1/xref/io/netty/example/proxy/package-summary.html

所以在ChannelInboundHandlerAdapter的子类中,我尝试这样做

ctx.pipeline().addLast(new EchoTestHandler("localhost", 3030));

我的EchoTestHandler看起来像:

public class EchoTestHandler extends ChannelInboundHandlerAdapter {

    private final String host;
    private final int port;
    private Channel outboundChannel;

    public EchoTestHandler(String host, int port) {
        System.out.println("constructor echo test handler");
        this.host = host;
        this.port = port;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("channel test handler");

        final Channel inboundChannel = ctx.channel();

        // start the connection attempt
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(inboundChannel.eventLoop())
                .channel(ctx.channel().getClass())
                .handler(new CryptoServerHandler(inboundChannel));
        ChannelFuture future = bootstrap.connect(host, port);
        outboundChannel = future.channel();
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) {
                if (channelFuture.isSuccess()) {
                    // connection complete, start to read first data
                    inboundChannel.read();
                } else {
                    // close the connection if connection attempt has failed
                    inboundChannel.close();
                }
            }
        });
    }
}

构造函数被调用,但由于它还没有连接任何东西,channelActive永远不会被调用。我也试过这个,更类似于代理示例:

ctx.pipeline().addLast(new EchoServerInitializer("localhost", 3020));

然后是EchoServerInitializer:

public class EchoServerInitializer extends ChannelInitializer<SocketChannel> {

    private final String host;
    private final int port;

    public EchoServerInitializer(String host, int port) {
        System.out.println("constructor EchoServerInitializer");
        this.host = host;
        this.port = port;
    }

    @Override
    public void initChannel(SocketChannel ch) {
        System.out.println("EchoServerInitializer initChannel");
        ch.pipeline().addLast(
                new LoggingHandler(LogLevel.INFO),
                new EchoServerHandler()
        );
    }

}

1 个答案:

答案 0 :(得分:1)

您需要与代理服务器连接以执行channelActive调用。代理示例使用8443端口,因此您可以使用命令telnet localhost 8443通过telnet(或其他方式)进行连接。