я запутался с методом «чтения» ChannelOutboundHandle в Netty Framework - PullRequest
0 голосов
/ 30 сентября 2018

У меня нет представления о методе «чтения» ChannelOutboundHandle.почему этот метод произошел в ChannelOutboundHandle, для чего он нужен?потому что outboundHandlers используются для обработки вывода, они обычно используются для записи данных в проводную сеть.а также у меня возникла проблема при использовании метода «read». Я написал EchoServer по netty.вот мой код:

public class EchoServer {

    public static void main(String[] args) {
        // this handler is sharable
        final EchoServerInboundHandler echoServerInboundHandler = new EchoServerInboundHandler();
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        // setup group
        serverBootstrap.group(eventLoopGroup)
                // setup channelFactory
                .channel(NioServerSocketChannel.class)
                // listening port
                .localAddress(new InetSocketAddress(8080))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(echoServerInboundHandler);
                        pipeline.addLast(new EchoServerOutboundHandler());
                    }
                });

        try {
            ChannelFuture f = serverBootstrap.bind().sync();
            f.addListener(new ChannelFutureListener() {
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        System.out.println(future.channel().localAddress()+" started!");
                    }
                }
            });
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            // release all threads
            eventLoopGroup.shutdownGracefully().syncUninterruptibly();

        }

    }
}

 public class EchoServerOutboundHandler extends ChannelOutboundHandlerAdapter {
    @Override
    public void read(ChannelHandlerContext ctx) throws Exception {
        System.out.println("read");
        //super.read(ctx);
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        System.out.println("msg:"+msg);
        super.write(ctx, msg, promise);
    }

    @Override
    public void flush(ChannelHandlerContext ctx) throws Exception {
        super.flush(ctx);
    }

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

}

@ChannelHandler.Sharable
public class EchoServerInboundHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ctx.writeAndFlush(msg);
    }

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

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("client:"+ctx.channel().remoteAddress()+" connected!");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        System.out.println("client:"+ctx.channel().remoteAddress()+" disconnected!");
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("EchoServerInboundHandler registered");
        super.channelRegistered(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("EchoServerInboundHandler unregistered");
        super.channelUnregistered(ctx);
    }
}

, как вы можете видеть, я комментирую super.read(ctx); в read методе EchoServerOutboundHandler, который вызываетпроблема в том, что он не может записать данные клиенту.а также я обнаружил, что этот метод будет вызываться, когда клиент установит соединение.

1 Ответ

0 голосов
/ 30 сентября 2018

По крайней мере, вам нужно предоставить тот же код, который родительский объект сделал бы в методе super () , который равен ctx.read()

.говорит ...

Звонки ChannelHandlerContext.read() ...

В противном случае все, что вы делаете, это печатаете что-то самостоятельно, а не используете Netty для обработки чего-либо,

...