Search in sources :

Example 16 with SimpleChannelInboundHandler

use of io.netty.channel.SimpleChannelInboundHandler in project BRFS by zhangnianli.

the class AsyncTcpClientGroup method createClient.

@Override
public TcpClient<BaseMessage, BaseResponse> createClient(TcpClientConfig config, Executor executor) throws InterruptedException {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.connectTimeoutMillis());
    if (executor == null) {
        executor = new Executor() {

            @Override
            public void execute(Runnable command) {
                command.run();
            }
        };
    }
    AsyncTcpClient client = new AsyncTcpClient(executor);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new IdleStateHandler(0, DEFAULT_WRITE_IDLE_TIMEOUT_SECONDS, 0)).addLast(new BaseMessageEncoder()).addLast(new BaseResponseDecoder()).addLast(new SimpleChannelInboundHandler<TokenMessage<BaseResponse>>() {

                @Override
                protected void channelRead0(ChannelHandlerContext ctx, TokenMessage<BaseResponse> msg) throws Exception {
                    client.handle(msg.messageToken(), msg.message());
                }

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt instanceof IdleStateEvent) {
                        IdleStateEvent e = (IdleStateEvent) evt;
                        if (e.state() == IdleState.WRITER_IDLE) {
                            ctx.writeAndFlush(new BaseMessage(-1));
                        }
                    }
                }
            });
        }
    });
    ChannelFuture future = bootstrap.connect(config.remoteAddress()).sync();
    if (!future.isSuccess()) {
        return null;
    }
    Channel channel = future.channel();
    channelList.add(channel);
    channel.closeFuture().addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            channelList.remove(channel);
        }
    });
    LOG.info("create tcp client for {}", config.remoteAddress());
    client.attach(channel);
    return client;
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) TokenMessage(com.bonree.brfs.common.net.tcp.TokenMessage) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelFutureListener(io.netty.channel.ChannelFutureListener) IOException(java.io.IOException) IdleStateEvent(io.netty.handler.timeout.IdleStateEvent) BaseResponse(com.bonree.brfs.common.net.tcp.BaseResponse) Executor(java.util.concurrent.Executor) AdaptiveRecvByteBufAllocator(io.netty.channel.AdaptiveRecvByteBufAllocator) BaseMessage(com.bonree.brfs.common.net.tcp.BaseMessage) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) Bootstrap(io.netty.bootstrap.Bootstrap)

Example 17 with SimpleChannelInboundHandler

use of io.netty.channel.SimpleChannelInboundHandler in project riposte by Nike-Inc.

the class ComponentTestUtils method executeRequest.

public static Pair<Integer, String> executeRequest(HttpRequest request, int port, int incompleteCallTimeoutMillis) throws Exception {
    Bootstrap bootstrap = new Bootstrap();
    EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    try {
        CompletableFuture<Pair<Integer, String>> responseFromServer = new CompletableFuture<>();
        bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new HttpClientCodec());
                p.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
                p.addLast(new SimpleChannelInboundHandler<HttpObject>() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
                        if (msg instanceof FullHttpResponse) {
                            // Store the proxyServer response for asserting on later.
                            FullHttpResponse responseMsg = (FullHttpResponse) msg;
                            responseFromServer.complete(Pair.of(responseMsg.getStatus().code(), responseMsg.content().toString(UTF_8)));
                        } else {
                            // Should never happen.
                            throw new RuntimeException("Received unexpected message type: " + msg.getClass());
                        }
                    }
                });
            }
        });
        // Connect to the proxyServer.
        Channel ch = bootstrap.connect("localhost", port).sync().channel();
        // Send the request.
        ch.writeAndFlush(request);
        // Wait for the response to be received
        try {
            responseFromServer.get(incompleteCallTimeoutMillis, TimeUnit.MILLISECONDS);
        } catch (TimeoutException ex) {
            fail("The call took much longer than expected without receiving a response. " + "Cancelling this test - it's not working properly", ex);
        } finally {
            ch.close();
        }
        // If we reach here then the call should be complete.
        return responseFromServer.get();
    } finally {
        eventLoopGroup.shutdownGracefully();
    }
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ChannelPipeline(io.netty.channel.ChannelPipeline) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) CompletableFuture(java.util.concurrent.CompletableFuture) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) HttpObject(io.netty.handler.codec.http.HttpObject) Bootstrap(io.netty.bootstrap.Bootstrap) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Pair(com.nike.internal.util.Pair) TimeoutException(java.util.concurrent.TimeoutException)

Example 18 with SimpleChannelInboundHandler

use of io.netty.channel.SimpleChannelInboundHandler in project activemq-artemis by apache.

the class NettyConnectorWithHTTPUpgradeTest method startWebServer.

private void startWebServer(int port) throws Exception {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    final SSLContext context;
    if (useSSL) {
        context = SSLSupport.createContext("JKS", SERVER_SIDE_KEYSTORE, PASSWORD, null, null, null);
    } else {
        context = null;
    }
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            // create a HTTP server
            ChannelPipeline p = ch.pipeline();
            if (useSSL) {
                SSLEngine engine = context.createSSLEngine();
                engine.setUseClientMode(false);
                SslHandler handler = new SslHandler(engine);
                p.addLast("ssl", handler);
            }
            p.addLast("decoder", new HttpRequestDecoder());
            p.addLast("encoder", new HttpResponseEncoder());
            p.addLast("http-upgrade-handler", new SimpleChannelInboundHandler<Object>() {

                // handle HTTP GET + Upgrade with a handshake specific to ActiveMQ Artemis remoting.
                @Override
                protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                    if (msg instanceof HttpRequest) {
                        HttpRequest request = (HttpRequest) msg;
                        for (Map.Entry<String, String> entry : request.headers()) {
                            System.out.println(entry);
                        }
                        String upgrade = request.headers().get(UPGRADE);
                        String secretKey = request.headers().get(SEC_ACTIVEMQ_REMOTING_KEY);
                        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, SWITCHING_PROTOCOLS);
                        response.headers().set(UPGRADE, upgrade);
                        response.headers().set(SEC_ACTIVEMQ_REMOTING_ACCEPT, createExpectedResponse(MAGIC_NUMBER, secretKey));
                        ctx.writeAndFlush(response);
                        // when the handshake is successful, the HTTP handlers are removed
                        ctx.pipeline().remove("decoder");
                        ctx.pipeline().remove("encoder");
                        ctx.pipeline().remove(this);
                        System.out.println("HTTP handshake sent, transferring channel");
                        // transfer the control of the channel to the Netty Acceptor
                        NettyAcceptor acceptor = (NettyAcceptor) server.getRemotingService().getAcceptor(acceptorName);
                        acceptor.transfer(ctx.channel());
                    // at this point, the HTTP upgrade process is over and the netty acceptor behaves like regular ones.
                    }
                }
            });
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            ctx.flush();
        }
    });
    b.bind(port).sync();
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) HttpRequest(io.netty.handler.codec.http.HttpRequest) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SSLEngine(javax.net.ssl.SSLEngine) NettyAcceptor(org.apache.activemq.artemis.core.remoting.impl.netty.NettyAcceptor) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) SSLContext(javax.net.ssl.SSLContext) RandomUtil.randomString(org.apache.activemq.artemis.tests.util.RandomUtil.randomString) SimpleString(org.apache.activemq.artemis.api.core.SimpleString) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ActiveMQNotConnectedException(org.apache.activemq.artemis.api.core.ActiveMQNotConnectedException) ActiveMQException(org.apache.activemq.artemis.api.core.ActiveMQException) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler) HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) Map(java.util.Map) HashMap(java.util.HashMap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 19 with SimpleChannelInboundHandler

use of io.netty.channel.SimpleChannelInboundHandler in project alibaba-mom by younfor.

the class DefaultConsumer method prepare.

@Override
public void prepare() {
    SIP = System.getProperty("SIP");
    if (SIP == null)
        SIP = "127.0.0.1";
    System.out.println("consumer connect:" + System.getProperty("SIP"));
    group = new NioEventLoopGroup();
    try {
        bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_KEEPALIVE, true).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel channel) throws Exception {
                channel.pipeline().addLast(new RpcEncoder()).addLast(new RpcDecoder()).addLast(new SimpleChannelInboundHandler<Object>() {

                    @Override
                    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                        connect();
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception {
                        logger.error("消费者异常关闭:");
                        e.printStackTrace();
                        ctx.close();
                    }

                    @Override
                    protected void channelRead0(final ChannelHandlerContext ctx, Object info) throws Exception {
                        logger.debug("client receive msg");
                        Message msg = (Message) info;
                        // 返回ACK
                        final ConsumeResult consumeResult = listener.onMessage(msg);
                        // 设置谁的 ack
                        consumeResult.setMsgId(msg.getMsgId());
                        /*
										 *设置 consumeResult来源
										 */
                        consumeResult.setGroupId(groupId);
                        consumeResult.setTopicAndFilter(new TopicAndFilter(topic, filterMap));
                        // if(Math.random()>0.95){
                        // new Thread(new Runnable(){
                        // 
                        // @Override
                        // public void run() {
                        // // TODO Auto-generated method stub
                        // try {
                        // Thread.sleep(10000);
                        // 
                        // ctx.writeAndFlush(consumeResult);
                        // } catch (InterruptedException e) {
                        // // TODO Auto-generated catch block
                        // e.printStackTrace();
                        // }
                        // }
                        // 
                        // }).start();;
                        // }else
                        ctx.writeAndFlush(consumeResult);
                    }
                });
            }
        });
        connect();
    } catch (InterruptedException e) {
        logger.error("消费者抛出异常  " + e.getMessage());
    }
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) TopicAndFilter(com.alibaba.middleware.race.mom.util.TopicAndFilter) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) RpcEncoder(com.alibaba.middleware.race.mom.serializer.RpcEncoder) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) RpcDecoder(com.alibaba.middleware.race.mom.serializer.RpcDecoder) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 20 with SimpleChannelInboundHandler

use of io.netty.channel.SimpleChannelInboundHandler in project alibaba-mom by younfor.

the class DefaultProducer method start.

@Override
public void start() {
    SIP = System.getProperty("SIP");
    if (SIP == null)
        SIP = "127.0.0.1";
    System.out.println("connect:" + System.getProperty("SIP"));
    group = new NioEventLoopGroup();
    bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel channel) throws Exception {
            channel.pipeline().addLast(new RpcEncoder()).addLast(new LineBasedFrameDecoder(1024 * 256)).addLast(new StringDecoder()).addLast(new SimpleChannelInboundHandler<Object>() {

                @Override
                public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                    logger.error("producer失去broker链接");
                    connect();
                }

                @Override
                protected void channelRead0(ChannelHandlerContext arg0, Object info) throws Exception {
                    logger.debug("recv ack: " + (String) info);
                    if (info != null) /*&&info.toString().startsWith("ackGroup"*/
                    {
                        String[] id = ((String) info).split("@");
                        // System.out.println(id.length+":len:"+id[0]+" | "+id[1]);
                        if (id[0].startsWith("fail")) {
                            // System.out.println("无人订阅");
                            SendResult sr = new SendResult();
                            sr.setMsgId(id[1]);
                            resultMap.get(id[1]).put(sr);
                        } else {
                            for (int i = 1; i < id.length; i++) {
                                // System.out.println(id[i]);
                                SendResult sr = new SendResult();
                                sr.setMsgId(id[i]);
                                resultMap.get(id[i]).put(sr);
                            }
                        }
                    // synchronized(lock){
                    // lock.notifyAll();
                    // }
                    } else {
                        // 异步方式接受数据
                        if (asyncResults.containsKey((String) info)) {
                            SendResult sr = new SendResult();
                            sr.setMsgId((String) info);
                            asyncResults.get((String) info).onResult(sr);
                            ;
                        } else {
                        }
                    }
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                    logger.error("--生产者的异常关闭--" + cause.getMessage());
                    cause.printStackTrace();
                    logger.error("重新连接");
                    ctx.close();
                    connect();
                }
            });
        }
    });
    connect();
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) RpcEncoder(com.alibaba.middleware.race.mom.serializer.RpcEncoder) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) StringDecoder(io.netty.handler.codec.string.StringDecoder) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Aggregations

ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)30 SimpleChannelInboundHandler (io.netty.channel.SimpleChannelInboundHandler)30 Channel (io.netty.channel.Channel)24 Bootstrap (io.netty.bootstrap.Bootstrap)19 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)19 SocketChannel (io.netty.channel.socket.SocketChannel)16 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)16 EventLoopGroup (io.netty.channel.EventLoopGroup)13 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)11 ChannelPipeline (io.netty.channel.ChannelPipeline)11 ByteBuf (io.netty.buffer.ByteBuf)9 ChannelFuture (io.netty.channel.ChannelFuture)9 CountDownLatch (java.util.concurrent.CountDownLatch)9 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)8 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)6 HttpRequest (io.netty.handler.codec.http.HttpRequest)6 IOException (java.io.IOException)6 Random (java.util.Random)6 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)5 InetSocketAddress (java.net.InetSocketAddress)5