Search in sources :

Example 6 with ChannelPromise

use of io.netty.channel.ChannelPromise in project MinecraftForge by MinecraftForge.

the class PacketLoggingHandler method register.

public static void register(NetworkManager manager) {
    ChannelPipeline pipeline = manager.channel().pipeline();
    final EnumPacketDirection direction = manager.getDirection();
    if (manager.isLocalChannel()) {
        pipeline.addBefore("packet_handler", "splitter", new SimpleChannelInboundHandler<Packet<?>>() {

            String prefix = (direction == EnumPacketDirection.SERVERBOUND ? "SERVER: C->S" : "CLIENT: S->C");

            @Override
            protected void channelRead0(ChannelHandlerContext ctx, Packet<?> msg) throws Exception {
                PacketBuffer buf = new PacketBuffer(Unpooled.buffer());
                msg.writePacketData(buf);
                FMLLog.log(Level.DEBUG, "%s %s:\n%s", prefix, msg.getClass().getSimpleName(), ByteBufUtils.getContentDump(buf));
                ctx.fireChannelRead(msg);
            }
        });
        pipeline.addBefore("splitter", "prepender", new ChannelOutboundHandlerAdapter() {

            String prefix = (direction == EnumPacketDirection.SERVERBOUND ? "SERVER: S->C" : "CLIENT: C->S");

            @Override
            public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                if (msg instanceof Packet<?>) {
                    PacketBuffer buf = new PacketBuffer(Unpooled.buffer());
                    ((Packet<?>) msg).writePacketData(buf);
                    FMLLog.log(Level.DEBUG, "%s %s:\n%s", prefix, msg.getClass().getSimpleName(), ByteBufUtils.getContentDump(buf));
                }
                ctx.write(msg, promise);
            }
        });
    } else {
        pipeline.replace("splitter", "splitter", new NettyVarint21FrameDecoder() {

            String prefix = (direction == EnumPacketDirection.SERVERBOUND ? "SERVER: C->S" : "CLIENT: S->C");

            @Override
            protected void decode(ChannelHandlerContext context, ByteBuf input, List<Object> output) throws Exception {
                super.decode(context, input, output);
                Iterator<Object> itr = output.iterator();
                while (itr.hasNext()) {
                    ByteBuf pkt = (ByteBuf) itr.next();
                    pkt.markReaderIndex();
                    FMLLog.log(Level.DEBUG, "%s:\n%s", prefix, ByteBufUtils.getContentDump(pkt));
                    pkt.resetReaderIndex();
                }
            }
        });
        pipeline.replace("prepender", "prepender", new NettyVarint21FrameEncoder() {

            String prefix = (direction == EnumPacketDirection.SERVERBOUND ? "SERVER: S->C" : "CLIENT: C->S");

            @Override
            protected void encode(ChannelHandlerContext context, ByteBuf input, ByteBuf output) throws Exception {
                input.markReaderIndex();
                FMLLog.log(Level.DEBUG, "%s:\n%s", prefix, ByteBufUtils.getContentDump(input));
                input.resetReaderIndex();
                super.encode(context, input, output);
            }
        });
    }
}
Also used : Packet(net.minecraft.network.Packet) NettyVarint21FrameDecoder(net.minecraft.network.NettyVarint21FrameDecoder) EnumPacketDirection(net.minecraft.network.EnumPacketDirection) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) ByteBuf(io.netty.buffer.ByteBuf) ChannelPipeline(io.netty.channel.ChannelPipeline) Iterator(java.util.Iterator) NettyVarint21FrameEncoder(net.minecraft.network.NettyVarint21FrameEncoder) PacketBuffer(net.minecraft.network.PacketBuffer)

Example 7 with ChannelPromise

use of io.netty.channel.ChannelPromise in project netty by netty.

the class HttpResponseHandler method channelRead0.

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
    Integer streamId = msg.headers().getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
    if (streamId == null) {
        System.err.println("HttpResponseHandler unexpected message received: " + msg);
        return;
    }
    Entry<ChannelFuture, ChannelPromise> entry = streamidPromiseMap.get(streamId);
    if (entry == null) {
        System.err.println("Message received for unknown stream id " + streamId);
    } else {
        // Do stuff with the message (for now just print it)
        ByteBuf content = msg.content();
        if (content.isReadable()) {
            int contentLength = content.readableBytes();
            byte[] arr = new byte[contentLength];
            content.readBytes(arr);
            System.out.println(new String(arr, 0, contentLength, CharsetUtil.UTF_8));
        }
        entry.getValue().setSuccess();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelPromise(io.netty.channel.ChannelPromise) ByteBuf(io.netty.buffer.ByteBuf)

Example 8 with ChannelPromise

use of io.netty.channel.ChannelPromise in project netty by netty.

the class HttpResponseHandler method awaitResponses.

/**
     * Wait (sequentially) for a time duration for each anticipated response
     *
     * @param timeout Value of time to wait for each response
     * @param unit Units associated with {@code timeout}
     * @see HttpResponseHandler#put(int, io.netty.channel.ChannelFuture, io.netty.channel.ChannelPromise)
     */
public void awaitResponses(long timeout, TimeUnit unit) {
    Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet().iterator();
    while (itr.hasNext()) {
        Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next();
        ChannelFuture writeFuture = entry.getValue().getKey();
        if (!writeFuture.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey());
        }
        if (!writeFuture.isSuccess()) {
            throw new RuntimeException(writeFuture.cause());
        }
        ChannelPromise promise = entry.getValue().getValue();
        if (!promise.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey());
        }
        if (!promise.isSuccess()) {
            throw new RuntimeException(promise.cause());
        }
        System.out.println("---Stream id: " + entry.getKey() + " received---");
        itr.remove();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Entry(java.util.Map.Entry) SimpleEntry(java.util.AbstractMap.SimpleEntry) ChannelPromise(io.netty.channel.ChannelPromise)

Example 9 with ChannelPromise

use of io.netty.channel.ChannelPromise in project netty by netty.

the class LocalChannelTest method testClosePeerInWritePromiseCompleteSameEventLoopPreservesOrder.

@Test
public void testClosePeerInWritePromiseCompleteSameEventLoopPreservesOrder() throws InterruptedException {
    Bootstrap cb = new Bootstrap();
    ServerBootstrap sb = new ServerBootstrap();
    final CountDownLatch messageLatch = new CountDownLatch(2);
    final CountDownLatch serverChannelLatch = new CountDownLatch(1);
    final ByteBuf data = Unpooled.wrappedBuffer(new byte[1024]);
    final AtomicReference<Channel> serverChannelRef = new AtomicReference<Channel>();
    try {
        cb.group(sharedGroup).channel(LocalChannel.class).handler(new TestHandler());
        sb.group(sharedGroup).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<LocalChannel>() {

            @Override
            public void initChannel(LocalChannel ch) throws Exception {
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        if (msg.equals(data)) {
                            ReferenceCountUtil.safeRelease(msg);
                            messageLatch.countDown();
                        } else {
                            super.channelRead(ctx, msg);
                        }
                    }

                    @Override
                    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                        messageLatch.countDown();
                        super.channelInactive(ctx);
                    }
                });
                serverChannelRef.set(ch);
                serverChannelLatch.countDown();
            }
        });
        Channel sc = null;
        Channel cc = null;
        try {
            // Start server
            sc = sb.bind(TEST_ADDRESS).syncUninterruptibly().channel();
            // Connect to the server
            cc = cb.connect(sc.localAddress()).syncUninterruptibly().channel();
            assertTrue(serverChannelLatch.await(5, SECONDS));
            final Channel ccCpy = cc;
            // Make sure a write operation is executed in the eventloop
            cc.pipeline().lastContext().executor().execute(new Runnable() {

                @Override
                public void run() {
                    ChannelPromise promise = ccCpy.newPromise();
                    promise.addListener(new ChannelFutureListener() {

                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            serverChannelRef.get().close();
                        }
                    });
                    ccCpy.writeAndFlush(data.retainedDuplicate(), promise);
                }
            });
            assertTrue(messageLatch.await(5, SECONDS));
            assertFalse(cc.isOpen());
            assertFalse(serverChannelRef.get().isOpen());
        } finally {
            closeChannel(cc);
            closeChannel(sc);
        }
    } finally {
        data.release();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) AbstractChannel(io.netty.channel.AbstractChannel) Channel(io.netty.channel.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ConnectException(java.net.ConnectException) ClosedChannelException(java.nio.channels.ClosedChannelException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 10 with ChannelPromise

use of io.netty.channel.ChannelPromise in project netty by netty.

the class LocalChannelTest method testConnectFutureBeforeChannelActive.

@Test(timeout = 3000)
public void testConnectFutureBeforeChannelActive() throws Exception {
    Bootstrap cb = new Bootstrap();
    ServerBootstrap sb = new ServerBootstrap();
    cb.group(group1).channel(LocalChannel.class).handler(new ChannelInboundHandlerAdapter());
    sb.group(group2).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<LocalChannel>() {

        @Override
        public void initChannel(LocalChannel ch) throws Exception {
            ch.pipeline().addLast(new TestHandler());
        }
    });
    Channel sc = null;
    Channel cc = null;
    try {
        // Start server
        sc = sb.bind(TEST_ADDRESS).sync().channel();
        cc = cb.register().sync().channel();
        final ChannelPromise promise = cc.newPromise();
        final Promise<Void> assertPromise = cc.eventLoop().newPromise();
        cc.pipeline().addLast(new TestHandler() {

            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                // Ensure the promise was done before the handler method is triggered.
                if (promise.isDone()) {
                    assertPromise.setSuccess(null);
                } else {
                    assertPromise.setFailure(new AssertionError("connect promise should be done"));
                }
            }
        });
        // Connect to the server
        cc.connect(sc.localAddress(), promise).sync();
        assertPromise.syncUninterruptibly();
        assertTrue(promise.isSuccess());
    } finally {
        closeChannel(cc);
        closeChannel(sc);
    }
}
Also used : AbstractChannel(io.netty.channel.AbstractChannel) Channel(io.netty.channel.Channel) ChannelPromise(io.netty.channel.ChannelPromise) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ConnectException(java.net.ConnectException) ClosedChannelException(java.nio.channels.ClosedChannelException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Aggregations

ChannelPromise (io.netty.channel.ChannelPromise)97 Test (org.junit.Test)56 DefaultChannelPromise (io.netty.channel.DefaultChannelPromise)34 ByteBuf (io.netty.buffer.ByteBuf)29 ChannelFuture (io.netty.channel.ChannelFuture)23 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)20 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)17 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)16 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)15 AsciiString (io.netty.util.AsciiString)14 Channel (io.netty.channel.Channel)10 ClosedChannelException (java.nio.channels.ClosedChannelException)10 InvocationOnMock (org.mockito.invocation.InvocationOnMock)10 ChannelFutureListener (io.netty.channel.ChannelFutureListener)9 Bootstrap (io.netty.bootstrap.Bootstrap)7 ConnectException (java.net.ConnectException)7 CountDownLatch (java.util.concurrent.CountDownLatch)7 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)6 AbstractChannel (io.netty.channel.AbstractChannel)6 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)6