Crystal
Crystal

Reputation: 29518

connect to client in netty in channelhandler

I'm trying to connect to another client from a server I'm building in Netty. I looked at the proxy example here: http://netty.io/4.1/xref/io/netty/example/proxy/package-summary.html

So in my subclass of ChannelInboundHandlerAdapter, I try to do this

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

My EchoTestHandler looks like:

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();
                }
            }
        });
    }
}

The constructor gets called, but since it does not connect to anything yet, channelActive never gets called. I also tried this, more similar to the proxy example:

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

And then 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()
        );
    }

}

Upvotes: 0

Views: 527

Answers (1)

Feedforward
Feedforward

Reputation: 4869

You need to connect with something to your proxy server to perform channelActive call. Proxy example uses 8443 port, so you can connect via telnet (or somethig else) using command telnet localhost 8443.

Upvotes: 1

Related Questions