Example usage for io.netty.channel ChannelHandlerContext flush

List of usage examples for io.netty.channel ChannelHandlerContext flush

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext flush.

Prototype

@Override
    ChannelHandlerContext flush();

Source Link

Usage

From source file:io.vertx.test.core.Http2ClientTest.java

License:Open Source License

@Test
public void testStreamError() throws Exception {
    waitFor(3);//  w  w w  .jav  a2  s .c o  m
    ServerBootstrap bootstrap = createH2Server((dec, enc) -> new Http2EventAdapter() {
        @Override
        public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                throws Http2Exception {
            enc.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("200"), 0, false,
                    ctx.newPromise());
            // Send a corrupted frame on purpose to check we get the corresponding error in the request exception handler
            // the error is : greater padding value 0c -> 1F
            // ChannelFuture a = encoder.frameWriter().writeData(request.context, id, Buffer.buffer("hello").getByteBuf(), 12, false, request.context.newPromise());
            // normal frame    : 00 00 12 00 08 00 00 00 03 0c 68 65 6c 6c 6f 00 00 00 00 00 00 00 00 00 00 00 00
            // corrupted frame : 00 00 12 00 08 00 00 00 03 1F 68 65 6c 6c 6f 00 00 00 00 00 00 00 00 00 00 00 00
            ctx.channel()
                    .write(Buffer.buffer(new byte[] { 0x00, 0x00, 0x12, 0x00, 0x08, 0x00, 0x00, 0x00,
                            (byte) (streamId & 0xFF), 0x1F, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x00,
                            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }).getByteBuf());
            ctx.flush();
        }
    });
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT).sync();
    try {
        Context ctx = vertx.getOrCreateContext();
        ctx.runOnContext(v -> {
            client.get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", resp -> {
                resp.exceptionHandler(err -> {
                    assertOnIOContext(ctx);
                    if (err instanceof Http2Exception) {
                        complete();
                    }
                });
            }).connectionHandler(conn -> {
                conn.exceptionHandler(err -> {
                    assertOnIOContext(ctx);
                    if (err instanceof Http2Exception) {
                        complete();
                    }
                });
            }).exceptionHandler(err -> {
                assertOnIOContext(ctx);
                if (err instanceof Http2Exception) {
                    complete();
                }
                /*
                */
            }).sendHead();
        });
        await();
    } finally {
        s.channel().close().sync();
    }
}

From source file:io.vertx.test.core.Http2ClientTest.java

License:Open Source License

@Test
public void testConnectionDecodeError() throws Exception {
    waitFor(3);//from   w  w w.ja v a2  s  . c o  m
    ServerBootstrap bootstrap = createH2Server((dec, enc) -> new Http2EventAdapter() {
        @Override
        public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                throws Http2Exception {
            enc.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("200"), 0, false,
                    ctx.newPromise());
            enc.frameWriter().writeRstStream(ctx, 10, 0, ctx.newPromise());
            ctx.flush();
        }
    });
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT).sync();
    try {
        Context ctx = vertx.getOrCreateContext();
        ctx.runOnContext(v -> {
            client.get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", resp -> {
                resp.exceptionHandler(err -> {
                    assertOnIOContext(ctx);
                    if (err instanceof Http2Exception) {
                        complete();
                    }
                });
            }).connectionHandler(conn -> {
                conn.exceptionHandler(err -> {
                    assertSame(ctx, Vertx.currentContext());
                    if (err instanceof Http2Exception) {
                        complete();
                    }
                });
            }).exceptionHandler(err -> {
                assertOnIOContext(ctx);
                if (err instanceof Http2Exception) {
                    complete();
                }
            }).sendHead();
        });
        await();
    } finally {
        s.channel().close().sync();
    }
}

From source file:io.vertx.test.core.Http2ClientTest.java

License:Open Source License

@Test
public void testInvalidServerResponse() throws Exception {
    ServerBootstrap bootstrap = createH2Server((dec, enc) -> new Http2EventAdapter() {
        @Override/*  w  w  w  .  j  a va  2s .c  o  m*/
        public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                throws Http2Exception {
            enc.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("xyz"), 0, false,
                    ctx.newPromise());
            ctx.flush();
        }
    });
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT).sync();
    try {
        Context ctx = vertx.getOrCreateContext();
        ctx.runOnContext(v -> {
            client.get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", resp -> {
                fail();
            }).connectionHandler(conn -> {
                conn.exceptionHandler(err -> {
                    fail();
                });
            }).exceptionHandler(err -> {
                assertOnIOContext(ctx);
                if (err instanceof NumberFormatException) {
                    testComplete();
                }
            }).end();
        });
        await();
    } finally {
        s.channel().close().sync();
    }
}

From source file:io.vertx.test.core.Http2ClientTest.java

License:Open Source License

private void testClearText(boolean upgrade) throws Exception {
    ServerBootstrap bootstrap = createH2CServer((dec, enc) -> new Http2EventAdapter() {
        @Override//  ww  w  . ja  v  a  2s. com
        public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                throws Http2Exception {
            enc.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("200"), 0, true, ctx.newPromise());
            ctx.flush();
        }
    }, upgrade);
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTP_HOST, DEFAULT_HTTP_PORT).sync();
    try {
        client.close();
        client = vertx.createHttpClient(
                clientOptions.setUseAlpn(false).setSsl(false).setHttp2ClearTextUpgrade(upgrade));
        client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
            assertEquals(HttpVersion.HTTP_2, resp.version());
            testComplete();
        }).exceptionHandler(this::fail).end();
        await();
    } finally {
        s.channel().close().sync();
    }
}

From source file:lunarion.cluster.coordinator.server.CoordinatorServerHandler.java

License:Open Source License

@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

    /*//w  w  w  . j  av  a2 s .  com
     * flushes first, then send data to socketChannel
     */
    ctx.flush();
}

From source file:me.ferrybig.javacoding.teamspeakconnector.internal.handler.ChannelWriteabilityQueueHandler.java

License:Open Source License

private void flushWhileWriteable(ChannelHandlerContext ctx) {
    do {//from   w ww . ja  va  2 s . co  m
        ChannelFuture f = queue.removeAndWrite();
        if (f == null || counter++ == 2) {
            counter = 0;
            ctx.flush();
        }
        if (f == null) {
            return;
        }
    } while (ctx.channel().isWritable());
}

From source file:net.hasor.rsf.console.TelnetHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    InetSocketAddress inetAddress = (InetSocketAddress) ctx.channel().remoteAddress();
    String remoteAddress = inetAddress.getAddress().getHostAddress();
    ////from   w  w w .  j  a  v a2  s . c o m
    boolean contains = false;
    for (String addr : this.inBoundAddress) {
        if (addr.equals(remoteAddress))
            contains = true;
    }
    //
    if (!contains) {
        logger.warn("rsfConsole -> reject inBound socket ,remoteAddress = {}.", remoteAddress);
        ctx.write("--------------------------------------------\r\n\r\n");
        ctx.write("I'm sorry you are not allowed to connect RSF Console.\r\n\r\n");
        ctx.write(" your address is :" + remoteAddress + "\r\n");
        ctx.write("--------------------------------------------\r\n");
        ctx.flush();
        ctx.close();
        return;
    } else {
        logger.info("rsfConsole -> accept inBound socket ,remoteAddress = {}.", remoteAddress);
    }
    //
    RsfSettings settings = this.rsfContext.getSettings();
    List<String> rsfAddressList = getStrings(settings.getBindAddressSet());
    //
    Attribute<RsfCommandSession> attr = ctx.attr(SessionKEY);
    if (attr.get() == null) {
        logger.info("rsfConsole -> new  RsfCommandSession.");
        attr.set(new RsfCommandSession(this.rsfContext, ctx));
    }
    logger.info("rsfConsole -> send Welcome info.");
    // Send greeting for a new connection.
    ctx.write("--------------------------------------------\r\n\r\n");
    ctx.write("Welcome to RSF Console!\r\n");
    ctx.write("\r\n");
    ctx.write("     login : " + new Date() + " now. form " + ctx.channel().remoteAddress() + "\r\n");
    ctx.write("    workAt : " + ctx.channel().localAddress() + "\r\n");
    for (int i = 0; i < rsfAddressList.size(); i++) {
        if (i == 0) {
            ctx.write("rsfAddress : " + rsfAddressList.get(i) + "\r\n");
        } else {
            ctx.write("           : " + rsfAddressList.get(i) + "\r\n");
        }
    }
    ctx.write("  unitName : " + this.rsfContext.getSettings().getUnitName() + "\r\n\r\n");
    ctx.write("Tips: You can enter a 'help' or 'help -a' for more information.\r\n");
    ctx.write("use the 'exit' or 'quit' out of the console.\r\n");
    ctx.write("--------------------------------------------\r\n");
    ctx.write(CMD);
    ctx.flush();
}

From source file:net.hasor.rsf.protocol.rsf.RsfEncoder.java

License:Apache License

protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
    try {//w  w  w  . j  av  a 2 s. co m
        if (msg instanceof RequestInfo) {
            RequestInfo info = (RequestInfo) msg;
            CodecAdapter factory = CodecAdapterFactory.getCodecAdapterByVersion(this.rsfEnvironment,
                    RsfConstants.Version_1);
            factory.wirteRequestBlock(factory.buildRequestBlock(info), out);
            return;
        }
        if (msg instanceof ResponseInfo) {
            ResponseInfo info = (ResponseInfo) msg;
            CodecAdapter factory = CodecAdapterFactory.getCodecAdapterByVersion(this.rsfEnvironment,
                    RsfConstants.Version_1);
            factory.wirteResponseBlock(factory.buildResponseBlock(info), out);
            return;
        }
        if (msg instanceof RequestBlock) {
            RequestBlock block = (RequestBlock) msg;
            CodecAdapter factory = CodecAdapterFactory.getCodecAdapterByVersion(this.rsfEnvironment,
                    RsfConstants.Version_1);
            factory.wirteRequestBlock(block, out);
            return;
        }
        if (msg instanceof ResponseBlock) {
            ResponseBlock block = (ResponseBlock) msg;
            CodecAdapter factory = CodecAdapterFactory.getCodecAdapterByVersion(this.rsfEnvironment,
                    RsfConstants.Version_1);
            factory.wirteResponseBlock(block, out);
            return;
        }
    } finally {
        ctx.flush();
    }
}

From source file:net.hasor.rsf.remoting.transport.netty.RSFProtocolEncoder.java

License:Apache License

public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    super.write(ctx, msg, promise);
    ctx.flush();
}

From source file:net.openhft.performance.tests.third.party.frameworks.netty.NettyEchoServer.java

License:Apache License

public void run() throws InterruptedException {
    @NotNull// ww w.j  a va 2s  .  c om
    EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
    @NotNull
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        @NotNull
        ServerBootstrap b = new ServerBootstrap(); // (2)
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // (3)
                .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                    @Override
                    public void initChannel(@NotNull SocketChannel ch) {
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            // echo server
                            @Override
                            public void channelRead(@NotNull ChannelHandlerContext ctx, Object msg) { // (2)
                                ctx.write(msg); // (1)
                                ctx.flush(); // (2)
                            }

                            @Override
                            public void exceptionCaught(@NotNull ChannelHandlerContext ctx,
                                    @NotNull Throwable cause) { // (4)
                                // Close the connection when an exception is raised.
                                cause.printStackTrace();
                                ctx.close();
                            }
                        });
                    }
                }).option(ChannelOption.SO_BACKLOG, 128) // (5)
                .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(port).sync(); // (7)

        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
        // shut down your server.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}