Java Examples for io.netty.channel.socket.nio.NioSocketChannel

The following java examples will help you to understand the usage of io.netty.channel.socket.nio.NioSocketChannel. These source code samples are taken from different open source projects.

Example 1
Project: NettyGameServer-master  File: GameNetProtoMessageTcpServerChannleInitializer.java View source code
@Override
protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
    ChannelPipeline channelPipLine = nioSocketChannel.pipeline();
    int maxLength = Integer.MAX_VALUE;
    channelPipLine.addLast("frame", new LengthFieldBasedFrameDecoder(maxLength, 2, 4, 0, 0));
    channelPipLine.addLast("encoder", new NetProtoBufMessageTCPEncoder());
    channelPipLine.addLast("decoder", new NetProtoBufMessageTCPDecoder());
    //        int readerIdleTimeSeconds = GlobalConstants.Net.SESSION_HEART_READ_TIMEOUT;
    //        int writerIdleTimeSeconds = GlobalConstants.Net.SESSION_HEART_WRITE_TIMEOUT;
    int readerIdleTimeSeconds = GlobalConstants.Net.SESSION_HEART_ALL_TIMEOUT;
    int writerIdleTimeSeconds = GlobalConstants.Net.SESSION_HEART_ALL_TIMEOUT;
    int allIdleTimeSeconds = GlobalConstants.Net.SESSION_HEART_ALL_TIMEOUT;
    channelPipLine.addLast("idleStateHandler", new IdleStateHandler(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds));
    channelPipLine.addLast("logger", new LoggingHandler(LogLevel.DEBUG));
    channelPipLine.addLast("handler", new GameNetMessageTcpServerHandler());
}
Example 2
Project: netty-in-action-master  File: BootstrapSharingEventLoopGroup.java View source code
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.channel(NioSocketChannel.class).handler(new SimpleChannelInboundHandler<ByteBuf>() {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
            System.out.println("Reveived data");
        }
    });
    bootstrap.group(ctx.channel().eventLoop());
    connectFuture = bootstrap.connect(new InetSocketAddress("www.manning.com", 80));
}
Example 3
Project: cpush-apns-master  File: BootstrapFactory.java View source code
public static SSLBootstrap create(final Credentials conf) {
    SSLBootstrap bootstrap = bootstrapMap.get(conf);
    if (bootstrap == null) {
        bootstrap = new SSLBootstrap(SecureSslContextFactory.getSSLContext(conf));
        bootstrap.group(workerGroup);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.remoteAddress(conf.getGateway().host(), conf.getGateway().port());
        bootstrap = bootstrapMap.putIfAbsent(conf, bootstrap);
    }
    return bootstrapMap.get(conf);
}
Example 4
Project: face2face-master  File: Client.java View source code
public static void beginPressTest() throws InterruptedException {
    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast("MessageDecoder", new PacketDecoder());
            p.addLast("MessageEncoder", new PacketEncoder());
            p.addLast(new ClientHandler());
        }
    });
    // Start the client.
    for (int i = 1; i <= clientNum; i++) {
        startConnection(b, i);
    }
}
Example 5
Project: learn_zk_netty-master  File: HelloWorldClient.java View source code
public static void main(String[] args) throws Exception {
    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }
    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                }
                p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)), new HelloWorldClientHandler());
            }
        });
        // Start the client.
        ChannelFuture channelFuture = bootstrap.connect(HOST, PORT).sync();
        // Wait until the connection is closed.
        channelFuture.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}
Example 6
Project: moco-master  File: MocoClient.java View source code
public void run(final String host, final int port, final ChannelHandler pipelineFactory) {
    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioSocketChannel.class).remoteAddress(host, port).option(ChannelOption.TCP_NODELAY, true).handler(pipelineFactory);
    try {
        Channel channel = bootstrap.connect().sync().channel();
        ChannelFuture future = channel.closeFuture().sync();
        future.addListener(ChannelFutureListener.CLOSE);
    } catch (InterruptedException e) {
        throw new MocoException(e);
    } finally {
        group.shutdownGracefully();
    }
}
Example 7
Project: netty-study-master  File: SubReqClient.java View source code
public void connect(int port, String host) throws Exception {
    // �置客户端NIO线程组
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                ch.pipeline().addLast(new ProtobufDecoder(SubscribeRespProto.SubscribeResp.getDefaultInstance()));
                ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                ch.pipeline().addLast(new ProtobufEncoder());
                ch.pipeline().addLast(new SubReqClientHandler());
            }
        });
        // �起异步连接�作
        ChannelFuture f = b.connect(host, port).sync();
        // 当代客户端链路关闭
        f.channel().closeFuture().sync();
    } finally {
        // 优雅退出,释放NIO线程组
        group.shutdownGracefully();
    }
}
Example 8
Project: redis-protocol-master  File: RedisClientBase.java View source code
public static Promise<RedisClientBase> connect(String host, int port) {
    final Queue<Promise<Reply>> queue = new LinkedList<>();
    SocketChannel socketChannel = new NioSocketChannel();
    final RedisClientBase client = new RedisClientBase(socketChannel, queue);
    socketChannel.pipeline().addLast(new RedisCommandEncoder(), new RedisReplyDecoder(), new SimpleChannelInboundHandler<Reply<?>>() {

        @Override
        protected void channelRead0(ChannelHandlerContext channelHandlerContext, Reply<?> reply) throws Exception {
            Promise<Reply> poll;
            synchronized (client) {
                poll = queue.poll();
                if (poll == null) {
                    throw new IllegalStateException("Promise queue is empty, received reply");
                }
            }
            poll.set(reply);
        }
    });
    final Promise<RedisClientBase> promise = new Promise<>();
    socketChannel.connect(new InetSocketAddress(host, port)).addListener(new ChannelFutureListenerPromiseAdapter<>(promise, client));
    return promise;
}
Example 9
Project: TOYS-master  File: DiscardClient.java View source code
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                }
                p.addLast(new DiscardClientHandler());
            }
        });
        // Make the connection attempt.
        ChannelFuture f = b.connect(HOST, PORT).sync();
        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
Example 10
Project: apn-socks-master  File: SocksServerConnectHandler.java View source code
@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {

        @Override
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                restLogger.info(request.host() + ":" + request.port() + "," + "T");
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType())).addListener(new ChannelFutureListener() {

                    @Override
                    public void operationComplete(ChannelFuture channelFuture) {
                        ctx.pipeline().remove(SocksServerConnectHandler.this);
                        outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                        ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                    }
                });
            } else {
                restLogger.info(request.host() + ":" + request.port() + "," + "F");
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
    final Channel inboundChannel = ctx.channel();
    b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true).handler(new DirectClientHandler(promise));
    b.connect(request.host(), request.port()).addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
            // Connection established use handler provided results
            } else {
                // Close the connection if the connection attempt has failed.
                restLogger.info(request.host() + ":" + request.port() + "," + "F");
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
}
Example 11
Project: casely-master  File: EchoClient.java View source code
public void run() throws Exception {
    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(//new LoggingHandler(LogLevel.INFO),
                new EchoClientHandler(firstMessageSize));
            }
        });
        // Start the client.
        ChannelFuture f = b.connect(host, port).sync();
        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}
Example 12
Project: com.dinstone.rpc-master  File: Server.java View source code
public static void main(String[] args) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_REUSEADDR, true).childHandler(new ChannelInitializer<NioSocketChannel>() {

        @Override
        protected void initChannel(NioSocketChannel ch) throws Exception {
            ch.pipeline().addLast(new SimpleServerHandler());
        }
    });
    b.bind(8090).sync().channel().closeFuture().sync();
}
Example 13
Project: divconq-master  File: CtpClient.java View source code
public void connect(String host, int port, OperationCallback connCallback) {
    // TODO maybe from session one day?
    this.adapter = new CtpAdapter();
    // OperationContext.get().getSession().allocateCtpAdapter();
    this.adapter.setHandler(this);
    EventLoopGroup el = Hub.instance.getEventLoopGroup();
    Bootstrap cb = new Bootstrap().group(el).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(//new LoggingHandler(LogLevel.INFO),
            new CtpHandler(CtpClient.this.adapter, false));
        }
    });
    // Start the client.
    try {
        cb.connect(host, port).sync();
    } catch (InterruptedException x) {
        System.out.println("Could not connect to Ctp Server");
        connCallback.error("Unable to connect: " + x);
        connCallback.callback();
        return;
    }
    System.out.println("Ctp Client - Connected");
    EngageCommand cmd = new EngageCommand();
    cmd.setBody(this.startRecord);
    this.startRecord = null;
    //System.out.println("Ctp Client - Init Sent");
    Task alive = new Task().withWork(new IWork() {

        @Override
        public void run(TaskRun trun) {
            try {
                CtpClient.this.adapter.sendCommand(CtpCommand.ALIVE);
            } catch (Exception x) {
                System.out.println("Ctp-F Client error: " + x);
            }
            trun.complete();
        }
    });
    this.sendCommand(cmd, new FuncCallback<RecordStruct>() {

        @Override
        public void callback() {
            if (!this.hasErrors())
                Hub.instance.getScheduler().runEvery(alive, 30);
            // we are willing to process more messages
            adapter.read();
            // if errors then caller should close
            connCallback.complete();
        }
    });
}
Example 14
Project: mspush-master  File: LightWeightClient.java View source code
@Override
public void start() {
    try {
        bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                //
                ch.pipeline().addLast(//
                new NettyEncoder(), //
                new NettyDecoder(), //
                new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()), new LightWeightClientHandler());
            }
        });
        // Start the client.
        ChannelFuture f = bootstrap.connect(host, port).sync();
        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}
Example 15
Project: netty-examples-master  File: Netty4ClientFactory.java View source code
protected Client createClient(String targetIP, int targetPort, int connectTimeout, String key) throws Exception {
    final Netty4ClientHandler handler = new Netty4ClientHandler(this, key);
    EventLoopGroup group = new NioEventLoopGroup(1);
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true"))).option(ChannelOption.SO_REUSEADDR, Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true"))).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout < 1000 ? 1000 : connectTimeout).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("decoder", new Netty4ProtocolDecoder());
            ch.pipeline().addLast("encoder", new Netty4ProtocolEncoder());
            ch.pipeline().addLast("handler", handler);
        }
    });
    ChannelFuture future = b.connect(targetIP, targetPort);
    future.awaitUninterruptibly(connectTimeout);
    if (!future.isDone()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " timeout!");
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " timeout!");
    }
    if (future.isCancelled()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
    }
    if (!future.isSuccess()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " error", future.cause());
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " error", future.cause());
    }
    Netty4Client client = new Netty4Client(future, key, connectTimeout);
    handler.setClient(client);
    return client;
}
Example 16
Project: netty.book.kor-master  File: EchoClient.java View source code
public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new EchoClientHandler1());
                p.addLast(new LoggingHandler());
            }
        });
        ChannelFuture f = b.connect("localhost", 8888).sync();
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
Example 17
Project: rpc4j-master  File: RpcClient.java View source code
public RpcResponse send(RpcRequest request) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel channel) throws Exception {
                channel.pipeline().addLast(new RpcEncoder(RpcRequest.class)).addLast(new RpcDecoder(RpcResponse.class)).addLast(RpcClient.this);
            }
        }).option(ChannelOption.SO_KEEPALIVE, true);
        ChannelFuture future = bootstrap.connect(host, port).sync();
        future.channel().writeAndFlush(request).sync();
        synchronized (obj) {
            obj.wait();
        }
        if (response != null) {
            future.channel().closeFuture().sync();
        }
        return response;
    } finally {
        group.shutdownGracefully();
    }
}
Example 18
Project: top-traffic-master  File: NettyConnection.java View source code
protected Channel connect() throws Throwable {
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) {
            preparePipeline(ch.pipeline());
        }
    });
    return b.connect(this.uri.getHost(), this.uri.getPort()).sync().channel();
}
Example 19
Project: astrix-master  File: NettyRemotingClient.java View source code
public void connect(String host, int port) {
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)), nettyRemotingClientHandler);
        }
    });
    // Start the connection attempt.
    ChannelFuture channel = b.connect(host, port);
    try {
        if (channel.await(1, TimeUnit.SECONDS)) {
            if (channel.isSuccess()) {
                return;
            }
        }
    } catch (InterruptedException e) {
    }
    destroy();
    throw new IllegalArgumentException(String.format("Failed to connect to remoting server: %s:%d", host, port));
}
Example 20
Project: failsafe-master  File: NettyExample.java View source code
static Bootstrap createBootstrap(EventLoopGroup group) {
    return new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

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

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

                @Override
                public void channelReadComplete(ChannelHandlerContext ctx) {
                    ctx.flush();
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                    // Close the connection when an exception is raised.
                    cause.printStackTrace();
                    ctx.close();
                }
            });
        }
    });
}
Example 21
Project: Glowstone-master  File: HttpClient.java View source code
public static void connect(String url, EventLoop eventLoop, HttpCallback callback) {
    URI uri = URI.create(url);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    SslContext sslCtx = null;
    if ("https".equalsIgnoreCase(scheme)) {
        if (port == -1)
            port = 443;
        try {
            sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        } catch (SSLException e) {
            callback.error(e);
            return;
        }
    } else if ("http".equalsIgnoreCase(scheme)) {
        if (port == -1)
            port = 80;
    } else {
        throw new IllegalArgumentException("Only http(s) is supported!");
    }
    new Bootstrap().group(eventLoop).resolver(resolverGroup).channel(Epoll.isAvailable() ? EpollSocketChannel.class : NioSocketChannel.class).handler(new HttpChannelInitializer(sslCtx, callback)).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000).connect(InetSocketAddress.createUnresolved(host, port)).addListener((ChannelFutureListener)  future -> {
        if (future.isSuccess()) {
            String path = uri.getRawPath() + (uri.getRawQuery() == null ? "" : "?" + uri.getRawQuery());
            HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
            request.headers().set(HttpHeaderNames.HOST, host);
            future.channel().writeAndFlush(request);
        } else {
            callback.error(future.cause());
        }
    });
}
Example 22
Project: gridcast-master  File: NodeClient.java View source code
public void initialize(final String host, int port, final EventLoopGroup workerGroup, final MessageRegistry messageRegistry, final ChannelInboundHandlerAdapter channelListener) throws InterruptedException {
    // prepare connection
    Bootstrap boot = new Bootstrap();
    boot.group(workerGroup);
    boot.channel(NioSocketChannel.class);
    boot.option(ChannelOption.SO_KEEPALIVE, true);
    boot.option(ChannelOption.TCP_NODELAY, true);
    boot.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            // encoders
            p.addLast(new LengthFieldPrepender(4));
            p.addLast(new ProtostuffEncoder(messageRegistry));
            // decoders
            p.addLast(new LengthFieldBasedFrameDecoder(0x100000, 0, 4, 0, 4));
            p.addLast(new ProtostuffDecoder(messageRegistry));
            p.addLast(channelListener);
        }
    });
    // connect
    channel = boot.connect(host, port).sync().channel();
}
Example 23
Project: gruffalo-master  File: GraphiteClientChannelInitializer.java View source code
private Bootstrap configureBootstrap() {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.remoteAddress(graphiteHost, graphitePort);
    bootstrap.group(eventLoopGroup);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.handler(this);
    bootstrap.option(ChannelOption.SO_LINGER, 0);
    bootstrap.option(ChannelOption.ALLOCATOR, UnpooledByteBufAllocator.DEFAULT);
    return bootstrap;
}
Example 24
Project: java-loggregator-master  File: LoggregatorClient.java View source code
public static void main(String[] args) throws Exception {
    final EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    final Bootstrap bootstrap = new Bootstrap().group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            final ChannelPipeline pipeline = socketChannel.pipeline();
            final SSLEngine engine = SSLContext.getDefault().createSSLEngine();
            engine.setUseClientMode(true);
            pipeline.addFirst("ssl", new SslHandler(engine)).addLast("http-codec", new HttpClientCodec()).addLast("aggregator", new HttpObjectAggregator(8192)).addLast("ws-handler", new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    if (msg instanceof BinaryWebSocketFrame) {
                        final BinaryWebSocketFrame frame = (BinaryWebSocketFrame) msg;
                        final ByteBufInputStream in = new ByteBufInputStream(frame.content());
                        final Messages.LogMessage logMessage = Messages.LogMessage.parseFrom(in);
                        System.out.println(logMessage);
                    } else {
                        System.out.println("Received unexpected object: " + msg);
                    }
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    cause.printStackTrace();
                }
            });
        }
    });
    bootstrap.connect("loggregator.cf2-dev.lds.org", 4443).addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                System.out.println("Connected to loggregator!");
            } else {
                future.cause().printStackTrace();
            }
        }
    }).sync();
}
Example 25
Project: jedis-netty-exploration-master  File: AsyncJedis.java View source code
public ChannelFuture connect() {
    Bootstrap b = new Bootstrap();
    this.workerGroup = new NioEventLoopGroup();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new RedisProtocolEncoder(), new RedisProtocolDecoder(outputs));
        }
    });
    this.f = b.connect(host, port);
    return f;
}
Example 26
Project: JGameDemo-master  File: TcpShortClient.java View source code
public static void start() {
    group = new NioEventLoopGroup();
    bootstrap.group(group).channel(NioSocketChannel.class);
    bootstrap.handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("encode", new ObjectEncoder());
            pipeline.addLast("decode", new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
            pipeline.addLast("handler", new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    ContextMsg contextMsg = new ContextMsg(ctx, msg);
                    AppClient.client.pushContextMsg(contextMsg);
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    // cause.printStackTrace();
                    ctx.close();
                }
            });
        }
    });
    bootstrap.option(ChannelOption.SO_KEEPALIVE, false);
}
Example 27
Project: JibbrJabbr-master  File: ReplIntegrationTest.java View source code
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
    ch.pipeline().addLast(new StringEncoder(US_ASCII)).addLast(new StringDecoder(US_ASCII)).addLast(new SimpleChannelInboundHandler<String>() {

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            failure.set(cause);
            ctx.close();
            latch.countDown();
        }

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            if (msg.equals(response.substring(0, msg.length()))) {
                response.delete(0, msg.length());
            }
            if (response.length() == 0) {
                ctx.close();
                latch.countDown();
            }
        }
    });
}
Example 28
Project: kixmpp-master  File: NodeClient.java View source code
public void initialize(final String host, int port, final EventLoopGroup workerGroup, final MessageRegistry messageRegistry, final ChannelInboundHandlerAdapter channelListener) throws InterruptedException {
    // prepare connection
    Bootstrap boot = new Bootstrap();
    boot.group(workerGroup);
    boot.channel(NioSocketChannel.class);
    boot.option(ChannelOption.SO_KEEPALIVE, true);
    boot.option(ChannelOption.TCP_NODELAY, true);
    boot.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            //p.addLast(new LoggingHandler());
            // encoders
            p.addLast(new LengthFieldPrepender(4));
            p.addLast(new ProtostuffEncoder(messageRegistry));
            // decoders
            p.addLast(new LengthFieldBasedFrameDecoder(0x100000, 0, 4, 0, 4));
            p.addLast(new ProtostuffDecoder(messageRegistry));
            p.addLast(channelListener);
        }
    });
    // connect
    channel = boot.connect(host, port).sync().channel();
}
Example 29
Project: mint4j-master  File: FactorialClient.java View source code
public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new FactorialClientInitializer(count));
        // Make a new connection.
        ChannelFuture f = b.connect(host, port).sync();
        // Get the handler instance to retrieve the answer.
        FactorialClientHandler handler = (FactorialClientHandler) f.channel().pipeline().last();
        // Print out the answer.
        System.err.format("Factorial of %,d is: %,d", count, handler.getFactorial());
    } finally {
        group.shutdownGracefully();
    }
}
Example 30
Project: miracle-framework-master  File: NettyClient.java View source code
@Override
public void connect(final InetSocketAddress socketAddress) {
    workerGroup = new NioEventLoopGroup(workerGroupThreads);
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.TCP_NODELAY, true).handler(applicationContext.getBean(serializeType.getClientChannelInitializer()));
    channel = bootstrap.connect(socketAddress.getAddress().getHostAddress(), socketAddress.getPort()).syncUninterruptibly().channel();
}
Example 31
Project: netty-book-master  File: NettyClient.java View source code
public void connect(int port, String host) throws Exception {
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4));
                ch.pipeline().addLast("MessageEncoder", new NettyMessageEncoder());
                ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50));
                ch.pipeline().addLast("LoginAuthHandler", new LoginAuthReqHandler());
                ch.pipeline().addLast("HeartBeatHandler", new HeartBeatReqHandler());
            }
        });
        // �起异步连接�作
        ChannelFuture future = b.connect(new InetSocketAddress(host, port), new InetSocketAddress(NettyConstant.LOCALIP, NettyConstant.LOCAL_PORT)).sync();
        future.channel().closeFuture().sync();
    } finally {
        // 所有资�释放完�之�,清空资�,�次�起�连�作
        executor.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    try {
                        // �起�连�作
                        connect(NettyConstant.PORT, NettyConstant.REMOTEIP);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
Example 32
Project: netty-cookbook-master  File: Http2Client.java View source code
public static void main(String[] args) throws Exception {
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    Http2ClientInitializer initializer = new Http2ClientInitializer(Integer.MAX_VALUE);
    try {
        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(initializer);
        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to [" + HOST + ':' + PORT + ']');
        // Wait for the HTTP/2 upgrade to occur.
        Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);
        HttpResponseHandler responseHandler = initializer.responseHandler();
        int streamId = 3;
        URI hostName = URI.create((SSL ? "https" : "http") + "://" + HOST + ':' + PORT);
        System.err.println("Sending request(s)...");
        if (URL != null) {
            // Create a simple GET request.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL);
            request.headers().addObject(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            channel.writeAndFlush(request);
            responseHandler.put(streamId, channel.newPromise());
            streamId += 2;
        }
        if (URL2 != null) {
            // Create a simple POST request with a body.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2, Unpooled.copiedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8)));
            request.headers().addObject(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            channel.writeAndFlush(request);
            responseHandler.put(streamId, channel.newPromise());
            streamId += 2;
        }
        responseHandler.awaitResponses(5, TimeUnit.SECONDS);
        System.out.println("Finished HTTP/2 request(s)");
        // Wait until the connection is closed.
        channel.close().syncUninterruptibly();
    } finally {
        workerGroup.shutdownGracefully();
    }
}
Example 33
Project: netty-master  File: KQueueSocketTestPermutation.java View source code
@SuppressWarnings("unchecked")
@Override
public List<BootstrapFactory<Bootstrap>> clientSocket() {
    return Arrays.asList(new BootstrapFactory<Bootstrap>() {

        @Override
        public Bootstrap newInstance() {
            return new Bootstrap().group(KQUEUE_WORKER_GROUP).channel(KQueueSocketChannel.class);
        }
    }, new BootstrapFactory<Bootstrap>() {

        @Override
        public Bootstrap newInstance() {
            return new Bootstrap().group(nioWorkerGroup).channel(NioSocketChannel.class);
        }
    });
}
Example 34
Project: netty-storm-master  File: NettyProducer.java View source code
static void connect() {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        // Configure SSL.
        //TODO Change the insecure Trust Manager Factory for a chain of trusted certificates...
        final SslContext sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
        Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new NettyConnectionInitializer(sslCtx, host, port));
        Channel channel = bootstrap.connect(host, port).sync().channel();
        NettyChannelSpecification nettyChannel = new NettyChannelSpecification(channel);
        //Simple JSONObject to ilustrate the example
        JSONObject objToSend = new JSONObject();
        objToSend.put("topic", "I Am Alive");
        while (true) {
            if (!channel.isActive()) {
                throw new java.nio.channels.ClosedChannelException();
            }
            //Keep sending the JSON Object until the channel drops...
            System.out.println("[Netty Producer] Sent to network: " + objToSend.toString());
            nettyChannel.send(objToSend);
            Thread.sleep(1000);
        }
    } catch (InterruptedException e) {
        System.err.println("[Netty Producer] Producer Interrupted, restarting the producer.");
        restart(group);
    } catch (SSLException e) {
        System.err.println("[Netty Producer] Restarting because it wasn't possible to establish a safe connection with the server :(");
        restart(group);
    } catch (ClosedChannelException e) {
        System.err.println("[Netty Producer] The channel has dropped...");
        restart(group);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        restart(group);
    }
}
Example 35
Project: netty4.0.27Learn-master  File: EpollSocketTestPermutation.java View source code
@Override
public List<BootstrapFactory<Bootstrap>> clientSocket() {
    return Arrays.asList(new BootstrapFactory<Bootstrap>() {

        @Override
        public Bootstrap newInstance() {
            return new Bootstrap().group(EPOLL_WORKER_GROUP).channel(EpollSocketChannel.class);
        }
    }, new BootstrapFactory<Bootstrap>() {

        @Override
        public Bootstrap newInstance() {
            return new Bootstrap().group(nioWorkerGroup).channel(NioSocketChannel.class);
        }
    });
}
Example 36
Project: netty4study-master  File: WebSocketClient.java View source code
public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        String protocol = uri.getScheme();
        if (!"ws".equals(protocol)) {
            throw new IllegalArgumentException("Unsupported protocol: " + protocol);
        }
        HttpHeaders customHeaders = new DefaultHttpHeaders();
        customHeaders.add("MyHeader", "MyValue");
        // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
        // If you change it to V00, ping is not supported and remember to change
        // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
        final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, customHeaders));
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("http-codec", new HttpClientCodec());
                pipeline.addLast("aggregator", new HttpObjectAggregator(8192));
                pipeline.addLast("ws-handler", handler);
            }
        });
        System.out.println("WebSocket Client connecting");
        Channel ch = b.connect(uri.getHost(), uri.getPort()).sync().channel();
        handler.handshakeFuture().sync();
        // Send 10 messages and wait for responses
        System.out.println("WebSocket Client sending message");
        for (int i = 0; i < 10; i++) {
            ch.writeAndFlush(new TextWebSocketFrame("Message #" + i));
        }
        // Ping
        System.out.println("WebSocket Client sending ping");
        ch.writeAndFlush(new PingWebSocketFrame(Unpooled.copiedBuffer(new byte[] { 1, 2, 3, 4, 5, 6 })));
        // Close
        System.out.println("WebSocket Client sending close");
        ch.writeAndFlush(new CloseWebSocketFrame());
        // WebSocketClientHandler will close the connection when the server
        // responds to the CloseWebSocketFrame.
        ch.closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
Example 37
Project: nettybook2-master  File: SecureChatClient.java View source code
public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new SecureChatClientInitializer(sslMode));
        // Start the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();
        // Read commands from the stdin.
        ChannelFuture lastWriteFuture = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (; ; ) {
            String line = in.readLine();
            if (line == null) {
                break;
            }
            // Sends the received line to the server.
            lastWriteFuture = ch.writeAndFlush(line + "\r\n");
            // the connection.
            if ("bye".equals(line.toLowerCase())) {
                ch.closeFuture().sync();
                break;
            }
        }
        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.sync();
        }
    } finally {
        // The connection is closed automatically on shutdown.
        group.shutdownGracefully();
    }
}
Example 38
Project: slow-light-master  File: TestClient.java View source code
private ChannelFuture connect() {
    final Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(new NioEventLoopGroup());
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.handler(new ClientChannelHandler(responseLock, responseCondition, response, responseSize));
    bootstrap.option(ChannelOption.AUTO_READ, false);
    return bootstrap.connect(LOCALHOST, port);
}
Example 39
Project: thundernetwork-master  File: P2PClient.java View source code
private void connect(NodeClient node) {
    try {
        System.out.println("Connect to " + node.host + ":" + node.port + " - " + node.intent);
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInit(contextFactory, node));
        // Start the connection attempt.
        Channel ch = b.connect(node.host, node.port).sync().channel();
        node.isConnected = ch.isOpen();
        ch.closeFuture().sync();
        System.out.println("Connection to " + node.host + " closed..");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 40
Project: weixin4j-master  File: Netty4HttpClientFactory.java View source code
private Bootstrap getBootstrap(final HttpParams params) {
    if (bootstrap == null) {
        bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel channel) throws Exception {
                ChannelPipeline pipeline = channel.pipeline();
                if (params != null) {
                    channel.config().setConnectTimeoutMillis(params.getConnectTimeout());
                    if (options != null) {
                        channel.config().setOptions(options);
                    }
                    pipeline.addLast(new ReadTimeoutHandler(params.getReadTimeout(), TimeUnit.MILLISECONDS));
                }
                pipeline.addLast(new HttpClientCodec());
                pipeline.addLast(new HttpContentDecompressor());
                pipeline.addLast(new ChunkedWriteHandler());
                pipeline.addLast(new HttpResponseDecoder());
                pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
            }
        });
    }
    return bootstrap;
}
Example 41
Project: apn-proxy-master  File: ApnProxyUserAgentTunnelHandler.java View source code
@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        final HttpRequest httpRequest = (HttpRequest) msg;
        //Channel uaChannel = uaChannelCtx.channel();
        // connect remote
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(uaChannelCtx.channel().eventLoop()).channel(NioSocketChannel.class).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).option(ChannelOption.AUTO_READ, false).handler(new ApnProxyTunnelChannelInitializer(uaChannelCtx.channel()));
        final ApnProxyRemote apnProxyRemote = uaChannelCtx.channel().attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote();
        // set local address
        if (StringUtils.isNotBlank(ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost()))) {
            bootstrap.localAddress(new InetSocketAddress((ApnProxyLocalAddressChooser.choose(apnProxyRemote.getRemoteHost())), 0));
        }
        bootstrap.connect(apnProxyRemote.getRemoteHost(), apnProxyRemote.getRemotePort()).addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(final ChannelFuture future1) throws Exception {
                if (future1.isSuccess()) {
                    if (apnProxyRemote.isAppleyRemoteRule()) {
                        uaChannelCtx.pipeline().remove("codec");
                        uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME);
                        uaChannelCtx.pipeline().remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME);
                        // add relay handler
                        uaChannelCtx.pipeline().addLast(new ApnProxyRelayHandler("UA --> Remote", future1.channel()));
                        future1.channel().writeAndFlush(Unpooled.copiedBuffer(constructConnectRequestForProxy(httpRequest, apnProxyRemote), CharsetUtil.UTF_8)).addListener(new ChannelFutureListener() {

                            @Override
                            public void operationComplete(ChannelFuture future2) throws Exception {
                                if (!future2.channel().config().getOption(ChannelOption.AUTO_READ)) {
                                    future2.channel().read();
                                }
                            }
                        });
                    } else {
                        HttpResponse proxyConnectSuccessResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, new HttpResponseStatus(200, "Connection established"));
                        uaChannelCtx.writeAndFlush(proxyConnectSuccessResponse).addListener(new ChannelFutureListener() {

                            @Override
                            public void operationComplete(ChannelFuture future2) throws Exception {
                                // remove handlers
                                uaChannelCtx.pipeline().remove("codec");
                                uaChannelCtx.pipeline().remove(ApnProxyPreHandler.HANDLER_NAME);
                                uaChannelCtx.pipeline().remove(ApnProxyUserAgentTunnelHandler.HANDLER_NAME);
                                // add relay handler
                                uaChannelCtx.pipeline().addLast(new ApnProxyRelayHandler("UA --> " + apnProxyRemote.getRemoteAddr(), future1.channel()));
                            }
                        });
                    }
                } else {
                    if (uaChannelCtx.channel().isActive()) {
                        uaChannelCtx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                    }
                }
            }
        });
    }
    ReferenceCountUtil.release(msg);
}
Example 42
Project: archistar-core-master  File: OzymandiasClient.java View source code
@SuppressFBWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON")
private Channel connectServer(int port) throws Exception {
    final OzymandiasClientHandler handler = new OzymandiasClientHandler(this);
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            SSLEngine engine = SSLContextFactory.getClientContext().createSSLEngine();
            engine.setUseClientMode(true);
            ch.pipeline().addLast(new SslHandler(engine), new ObjectEncoder(), new ObjectDecoder(OzymandiasServer.maxObjectSize, ClassResolvers.cacheDisabled(null)), handler);
        }
    });
    return b.connect("127.0.0.1", port).sync().channel();
}
Example 43
Project: bergamot-master  File: WebHookEngine.java View source code
@Override
public void sendNotification(Notification notification) {
    // we only handle check notifications
    if (notification instanceof CheckNotification) {
        // the webhook URL is stored as a check parameter
        for (String webhookUrl : this.findNotificationParameters((CheckNotification) notification, "webhook.url")) {
            try {
                URL url = new URL(webhookUrl);
                // build the request to send
                FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, url.getPath(), Unpooled.wrappedBuffer(this.transcoder.encodeAsBytes(notification)));
                request.headers().add(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
                request.headers().add(HttpHeaders.Names.HOST, url.getPort() == -1 ? url.getHost() : url.getHost() + ":" + url.getPort());
                request.headers().add(HttpHeaders.Names.USER_AGENT, "Bergamot Monitoring WebHook 1.1.0");
                request.headers().add(HttpHeaders.Names.CONTENT_TYPE, "application/json; charset=utf-8");
                request.headers().add(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
                // make a HTTP request
                Bootstrap b = new Bootstrap();
                b.group(this.eventLoop);
                b.channel(NioSocketChannel.class);
                b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) TimeUnit.SECONDS.toMillis(60));
                b.handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        // SSL handling
                        SSLEngine sslEngine = null;
                        if ("https".equalsIgnoreCase(url.getProtocol())) {
                            sslEngine = sslContext.createSSLEngine(url.getHost(), url.getPort() == -1 ? 443 : url.getPort());
                            sslEngine.setUseClientMode(true);
                            SSLParameters params = new SSLParameters();
                            params.setEndpointIdentificationAlgorithm("HTTPS");
                            sslEngine.setSSLParameters(params);
                            ch.pipeline().addLast(new SslHandler(sslEngine));
                        }
                        // HTTP handling
                        ch.pipeline().addLast(new HttpClientCodec(), new HttpContentDecompressor(), new HttpObjectAggregator(1 * 1024 * 1024), new WebHookClientHandler(timer, sslEngine, request));
                    }
                });
                // connect the client
                b.connect(url.getHost(), url.getPort() == -1 ? url.getDefaultPort() : url.getPort());
                // accounting
                this.accounting.account(new SendNotificationToContactAccountingEvent(notification.getSite().getId(), notification.getId(), getObjectId(notification), getNotificationType(notification), null, this.getName(), "webhook", url.toString(), null));
            } catch (MalformedURLException e) {
                logger.error("Cannot send WebHook to malformed url", e);
            }
        }
    }
}
Example 44
Project: bgpcep-master  File: PCCDispatcherImpl.java View source code
private static void setChannelFactory(final Bootstrap bootstrap, final Optional<KeyMapping> keys) {
    if (Epoll.isAvailable()) {
        bootstrap.channel(EpollSocketChannel.class);
        bootstrap.option(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
    } else {
        bootstrap.channel(NioSocketChannel.class);
    }
    if (keys.isPresent()) {
        if (Epoll.isAvailable()) {
            bootstrap.option(EpollChannelOption.TCP_MD5SIG, keys.get());
        } else {
            throw new UnsupportedOperationException(Epoll.unavailabilityCause().getCause());
        }
    }
}
Example 45
Project: BrowserPush-master  File: WebSocket.java View source code
void createBootstrap() throws InterruptedException {
    bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("http-codec", new HttpClientCodec());
            pipeline.addLast("aggregator", new HttpObjectAggregator(8192));
            pipeline.addLast("ws-handler", handler);
        }
    });
    channel = bootstrap.connect(uri.getHost(), uri.getPort()).sync().channel();
}
Example 46
Project: camel-master  File: LumberjackUtil.java View source code
static List<Integer> sendMessages(int port, SSLContextParameters sslContextParameters) throws InterruptedException {
    NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    try {
        // This list will hold the acknowledgment response sequence numbers
        List<Integer> responses = new ArrayList<>();
        // This initializer configures the SSL and an acknowledgment recorder
        ChannelInitializer<Channel> initializer = new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                if (sslContextParameters != null) {
                    SSLEngine sslEngine = sslContextParameters.createSSLContext(null).createSSLEngine();
                    sslEngine.setUseClientMode(true);
                    pipeline.addLast(new SslHandler(sslEngine));
                }
                // Add the response recorder
                pipeline.addLast(new SimpleChannelInboundHandler<ByteBuf>() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
                        assertEquals(msg.readUnsignedByte(), (short) '2');
                        assertEquals(msg.readUnsignedByte(), (short) 'A');
                        synchronized (responses) {
                            responses.add(msg.readInt());
                        }
                    }
                });
            }
        };
        // Connect to the server
        Channel channel = //
        new Bootstrap().group(//
        eventLoopGroup).channel(//
        NioSocketChannel.class).handler(//
        initializer).connect("127.0.0.1", //
        port).sync().channel();
        // Send the 2 window frames
        TimeUnit.MILLISECONDS.sleep(100);
        channel.writeAndFlush(readSample("io/window10"));
        TimeUnit.MILLISECONDS.sleep(100);
        channel.writeAndFlush(readSample("io/window15"));
        TimeUnit.MILLISECONDS.sleep(100);
        channel.close();
        synchronized (responses) {
            return responses;
        }
    } finally {
        eventLoopGroup.shutdownGracefully();
    }
}
Example 47
Project: carbondata-master  File: DictionaryClient.java View source code
/**
   * start dictionary client
   *
   * @param address
   * @param port
   */
public void startClient(String address, int port) {
    LOGGER.audit("Starting client on " + address + " " + port);
    long start = System.currentTimeMillis();
    // Create an Event with 1 thread.
    workerGroup = new NioEventLoopGroup(1);
    Bootstrap clientBootstrap = new Bootstrap();
    clientBootstrap.group(workerGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            // Based on length provided at header, it collects all packets
            pipeline.addLast("LengthDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 2, 0, 2));
            pipeline.addLast("DictionaryClientHandler", dictionaryClientHandler);
        }
    });
    clientBootstrap.connect(new InetSocketAddress(address, port));
    LOGGER.info("Dictionary client Started, Total time spent : " + (System.currentTimeMillis() - start));
}
Example 48
Project: CmRaft-master  File: TestNettyClient.java View source code
public void connect() throws Exception {
    String host = "localhost";
    int port = 13888;
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        // (1)
        Bootstrap b = new Bootstrap();
        // (2)
        b.group(workerGroup);
        // (3)
        b.channel(NioSocketChannel.class);
        // (4)
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast("decoder", new LengthFieldBasedFrameDecoder(100000000, 0, 4, 0, 4));
                ch.pipeline().addLast("encoder", new LengthFieldPrepender(4));
                ch.pipeline().addLast(new TestNettyClientHandler());
            }
        });
        // Start the client.
        // (5)
        ChannelFuture f = b.connect(host, port).sync();
        System.out.println("connected");
        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
    }
}
Example 49
Project: deep-spark-master  File: ExtractorClient.java View source code
public ExtractorClient initialize() throws DeepExtractorInitializationException {
    try {
        // Configure SSL.
        final SslContext sslCtx;
        if (SSL) {
            sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
        } else {
            sslCtx = null;
        }
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ExtractorClientInitializer<T>(sslCtx));
        // Make a new connection.
        this.ch = b.connect(HOST, PORT).sync().channel();
        // Get the handler instance to initiate the request.
        this.handler = ch.pipeline().get(ExtractorClientHandler.class);
    } catch (SSLExceptionInterruptedException |  e) {
        throw new DeepExtractorInitializationException(e);
    }
    return this;
}
Example 50
Project: dubbo-plus-master  File: Netty4Client.java View source code
@Override
protected void doOpen() throws Throwable {
    EventLoopGroup bossGroup = new NioEventLoopGroup(Constants.DEFAULT_IO_THREADS, new NamedThreadFactory("NettyClientBoss", true));
    final Netty4Handler nettyHandler = new Netty4Handler(getUrl(), this);
    bootstrap = new Bootstrap();
    bootstrap.group(bossGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout()).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<NioSocketChannel>() {

        @Override
        protected void initChannel(NioSocketChannel ch) throws Exception {
            Netty4CodecAdapter adapter = new Netty4CodecAdapter(getCodec(), getUrl(), Netty4Client.this);
            ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("encoder", adapter.getEncoder()).addLast("handler", nettyHandler);
        }
    });
}
Example 51
Project: etcd4j-master  File: EtcdNettyClientTest.java View source code
@Test
public void testConfig() throws Exception {
    try {
        NioEventLoopGroup evl = new NioEventLoopGroup();
        EtcdNettyConfig config = new EtcdNettyConfig().setConnectTimeout(100).setSocketChannelClass(NioSocketChannel.class).setMaxFrameSize(1024 * 1024).setEventLoopGroup(evl).setHostName("localhost");
        EtcdNettyClient client = new EtcdNettyClient(config, ETCD_URI);
        Bootstrap bootstrap = client.getBootstrap();
        Channel channel = bootstrap.connect(ETCD_URI.getHost(), ETCD_URI.getPort()).sync().channel();
        assertEquals(evl, bootstrap.config().group());
        assertEquals(100, channel.config().getOption(ChannelOption.CONNECT_TIMEOUT_MILLIS).intValue());
    } catch (Throwable t) {
        LOGGER.warn("", t);
        throw t;
    }
}
Example 52
Project: ethereumj-master  File: PeerClient.java View source code
public ChannelFuture connectAsync(String host, int port, String remoteId, boolean discoveryMode) {
    ethereumListener.trace("Connecting to: " + host + ":" + port);
    EthereumChannelInitializer ethereumChannelInitializer = ctx.getBean(EthereumChannelInitializer.class, remoteId);
    ethereumChannelInitializer.setPeerDiscoveryMode(discoveryMode);
    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.peerConnectionTimeout());
    b.remoteAddress(host, port);
    b.handler(ethereumChannelInitializer);
    // Start the client.
    return b.connect();
}
Example 53
Project: hasor-master  File: TelnetClient.java View source code
public static void execCommand(String host, int port, final String command, Map<String, String> envMap) throws Exception {
    StringWriter commands = new StringWriter();
    if (envMap != null) {
        for (String key : envMap.keySet()) {
            String val = envMap.get(key);
            commands.write("set " + key + " = " + val + " \n");
        }
    }
    commands.write("set SESSION_AFTERCLOSE = true \n");
    commands.write(command + "\n");
    //
    EventLoopGroup group = new NioEventLoopGroup();
    final BasicFuture<Object> closeFuture = new BasicFuture<Object>();
    final AtomicBoolean atomicBoolean = new AtomicBoolean(true);
    try {
        Bootstrap b = new Bootstrap();
        b = b.group(group);
        b = b.channel(NioSocketChannel.class);
        b = b.handler(new ChannelInitializer<SocketChannel>() {

            public void initChannel(SocketChannel ch) {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                pipeline.addLast(new StringDecoder());
                pipeline.addLast(new StringEncoder());
                pipeline.addLast(new TelnetClientHandler(closeFuture, atomicBoolean));
            }
        });
        Channel ch = b.connect(host, port).sync().channel();
        ChannelFuture lastWriteFuture = null;
        BufferedReader commandReader = new BufferedReader(new StringReader(commands.toString()));
        for (; ; ) {
            if (atomicBoolean.get()) {
                String line = commandReader.readLine();
                if (line == null) {
                    break;
                }
                if (ch.isActive()) {
                    atomicBoolean.set(false);
                    lastWriteFuture = ch.writeAndFlush(line + "\r\n");
                }
            } else {
                //等待指令的�应
                Thread.sleep(500);
            }
        }
        if (lastWriteFuture != null) {
            lastWriteFuture.sync();
        }
    } finally {
        closeFuture.get();
        group.shutdownGracefully();
    }
}
Example 54
Project: hbase-master  File: TestNettyIPC.java View source code
private void setConf(Configuration conf) {
    switch(eventLoopType) {
        case "nio":
            NettyRpcClientConfigHelper.setEventLoopConfig(conf, NIO, NioSocketChannel.class);
            break;
        case "epoll":
            NettyRpcClientConfigHelper.setEventLoopConfig(conf, EPOLL, EpollSocketChannel.class);
            break;
        case "perClientNio":
            NettyRpcClientConfigHelper.createEventLoopPerClient(conf);
            break;
        default:
            break;
    }
}
Example 55
Project: jts-tanks-master  File: GameServer.java View source code
private static void startNetworkClient() {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.channel(NioSocketChannel.class).handler(new Game2AuthChannelInitializer());
    String host = GameServerProperty.getInstance().AUTH_CLIENT_HOST;
    int port = GameServerProperty.getInstance().AUTH_CLIENT_PORT;
    bootstrap.remoteAddress(host, port);
    NetworkThread clientsNetworkThread = new NetworkThread(bootstrap, false);
    clientsNetworkThread.start();
    log.info("Connect to auth on {}:{}", host, port);
}
Example 56
Project: kinetic-java-master  File: TcpNioTransportProvider.java View source code
private void initTransport() throws KineticException {
    this.port = this.config.getPort();
    this.host = this.config.getHost();
    try {
        workerGroup = NioWorkerGroup.getWorkerGroup();
        nioChannelInitializer = new NioChannelInitializer(this.mservice);
        bootstrap = new Bootstrap();
        bootstrap.group(workerGroup).channel(NioSocketChannel.class).handler(nioChannelInitializer);
        if (config.getLocalAddress() == null) {
            channel = bootstrap.connect(host, port).sync().channel();
        } else {
            // remote address
            InetSocketAddress remote = new InetSocketAddress(host, port);
            // remote port
            InetSocketAddress local = new InetSocketAddress(config.getLocalAddress(), config.getLocalPort());
            channel = bootstrap.connect(remote, local).sync().channel();
            logger.info("connected to remote with local address: " + config.getLocalAddress() + ", local port=" + config.getLocalPort());
        }
    } catch (Exception e) {
        this.close();
        throw new KineticException(e);
    }
    logger.info("TcpNio client transport provider connecting to host:port =" + host + ":" + port);
}
Example 57
Project: lb-quickfixj-master  File: NettySocketInitiator.java View source code
// *************************************************************************
//
// *************************************************************************
/**
     *
     */
@Override
public void connect() {
    try {
        m_boot = new Bootstrap();
        m_boot.group(new NioEventLoopGroup());
        m_boot.channel(NioSocketChannel.class);
        m_boot.option(ChannelOption.SO_KEEPALIVE, true);
        m_boot.option(ChannelOption.TCP_NODELAY, true);
        m_boot.option(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));
        m_boot.handler(new NettyChannelInitializer(this, getHelper(), FIXSessionType.INITIATOR));
        SessionID sid = getHelper().getSession().getSessionID();
        String host = getHelper().getSettings().getString("SocketConnectHost");
        int port = getHelper().getSettings().getInt("SocketConnectPort");
        m_boot.remoteAddress(new InetSocketAddress(host, port));
        if (!isRunning()) {
            setRunning(true);
            doConnect();
        }
    } catch (Exception e) {
        LOGGER.warn("Exception", e);
        setRunning(false);
    }
}
Example 58
Project: lightsocks-java-master  File: SLeftHandler.java View source code
public void run() throws Exception {
    // EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(workerGroup).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(// new LoggingHandler(LogLevel.INFO),
                new SRightHandler(forwardWrite));
            }
        });
        // Start the client.
        System.out.println(host.toString() + ":" + port);
        ChannelFuture f = b.connect(host, port).sync();
    // Wait until the connection is closed.
    // f.channel().closeFuture().sync();
    } finally {
    // Shut down the event loop to terminate all threads.
    // group.shutdownGracefully();
    }
}
Example 59
Project: MINA-master  File: Netty4TcpBenchmarkClient.java View source code
/**
     * {@inheritedDoc}
     */
public void start(final int port, final CountDownLatch counter, final byte[] data) throws IOException {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group);
    bootstrap.option(ChannelOption.SO_SNDBUF, 64 * 1024);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                private void sendMessage(ChannelHandlerContext ctx, byte[] data) {
                    ByteBuf buf = ctx.alloc().buffer(data.length);
                    buf.writeBytes(data);
                    ctx.writeAndFlush(buf);
                }

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object message) throws Exception {
                    ByteBuf buf = (ByteBuf) message;
                    for (int i = 0; i < buf.readableBytes(); i++) {
                        counter.countDown();
                        if (counter.getCount() > 0) {
                            sendMessage(ctx, data);
                        } else {
                            ctx.channel().close();
                        }
                    }
                    buf.release();
                }

                @Override
                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                    sendMessage(ctx, data);
                }
            });
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            cause.printStackTrace();
            ctx.close();
        }
    });
    bootstrap.connect(new InetSocketAddress(port));
}
Example 60
Project: mockserver-master  File: RelayConnectHandler.java View source code
@Override
public void channelRead0(final ChannelHandlerContext serverCtx, final T request) throws Exception {
    Bootstrap bootstrap = new Bootstrap().group(serverCtx.channel().eventLoop()).channel(NioSocketChannel.class).handler(new ChannelInboundHandlerAdapter() {

        @Override
        public void channelActive(final ChannelHandlerContext clientCtx) throws Exception {
            serverCtx.channel().writeAndFlush(successResponse(request)).addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    removeCodecSupport(serverCtx);
                    // downstream
                    ChannelPipeline downstreamPipeline = clientCtx.channel().pipeline();
                    if (PortUnificationHandler.isSslEnabledDownstream(serverCtx.channel())) {
                        downstreamPipeline.addLast(new SslHandler(SSLFactory.createClientSSLEngine()));
                    }
                    if (logger.isDebugEnabled()) {
                        downstreamPipeline.addLast(new LoggingHandler(this.getClass().getSimpleName() + "                -->"));
                    }
                    downstreamPipeline.addLast(new HttpClientCodec());
                    downstreamPipeline.addLast(new HttpContentDecompressor());
                    downstreamPipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
                    downstreamPipeline.addLast(new DownstreamProxyRelayHandler(serverCtx.channel(), logger));
                    // upstream
                    ChannelPipeline upstreamPipeline = serverCtx.channel().pipeline();
                    if (PortUnificationHandler.isSslEnabledUpstream(serverCtx.channel())) {
                        upstreamPipeline.addLast(new SslHandler(SSLFactory.createServerSSLEngine()));
                    }
                    if (logger.isDebugEnabled()) {
                        upstreamPipeline.addLast(new LoggingHandler(this.getClass().getSimpleName() + "<-- "));
                    }
                    upstreamPipeline.addLast(new HttpServerCodec());
                    upstreamPipeline.addLast(new HttpContentDecompressor());
                    upstreamPipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
                    upstreamPipeline.addLast(new UpstreamProxyRelayHandler(clientCtx.channel(), logger));
                }
            });
        }
    });
    final InetSocketAddress remoteSocket = getDownstreamSocket(serverCtx.channel());
    bootstrap.connect(remoteSocket).addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                failure("Connection failed to " + remoteSocket, future.cause(), serverCtx, failureResponse(request));
            }
        }
    });
}
Example 61
Project: Mycat-BigSQL-master  File: MycatStartup.java View source code
public void run() throws Exception {
    SystemConfig sysConf = MycatSystem.getInstance().getConfig().getSystem();
    int serverPort = sysConf.getServerPort();
    String serverIp = sysConf.getBindIp();
    int processorCount = sysConf.getProcessors();
    // (1)
    EventLoopGroup bossGroup = new NioEventLoopGroup(processorCount);
    EventLoopGroup workerGroup = bossGroup;
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<// (4)
        SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new MySQLProtocalDecoder(), new FrontMysqlProtocalHandler());
            }
        }).option(ChannelOption// (5)
        .SO_BACKLOG, 128).childOption(// (6)
        ChannelOption.SO_KEEPALIVE, true);
        MycatSystem.getInstance().getConfig().getSystem().setSocketParams(b, true);
        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(new InetSocketAddress(serverIp, serverPort// (7)
        )).sync();
        Bootstrap cb = MycatSystem.getInstance().getSoketConnetor();
        cb.group(workerGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<NioSocketChannel>() {

            @Override
            public void initChannel(NioSocketChannel ch) throws Exception {
                ch.pipeline().addLast(new MySQLProtocalDecoder(), new BackendMySQLProtocalHandler());
            }
        });
        MycatSystem.getInstance().getConfig().getSystem().setSocketParams(cb, false);
        System.out.println("server started");
        // init datahost
        Map<String, PhysicalDBPool> dataHosts = MycatSystem.getInstance().getConfig().getDataHosts();
        LOGGER.info("Initialize dataHost ...");
        for (PhysicalDBPool node : dataHosts.values()) {
            int index = 0;
            // String index = dnIndexProperties.getProperty(
            // node.getHostName(), "0");
            // if (!"0".equals(index)) {
            // LOGGER.info("init datahost: " + node.getHostName()
            // + "  to use datasource index:" + index);
            // }
            node.init(Integer.valueOf(index));
        // node.startHeartbeat();
        }
        System.out.println("MyCAT Server startup successfully. see logs in logs/mycat.log");
        // 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 {
        System.out.println("stoped");
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
Example 62
Project: myLib-master  File: ClientTest.java View source code
public void connect() throws Exception {
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        Bootstrap bootstrap = new Bootstrap().group(workerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new ClientEncoder()).addLast(new ClientHandler());
            }
        });
        ChannelFuture f = bootstrap.connect("localhost", 12345).sync();
        System.out.println("connected");
        f.channel().closeFuture().sync();
        System.out.println("synced.");
    } finally {
        workerGroup.shutdownGracefully();
    }
}
Example 63
Project: nfs-rpc-master  File: Netty4ClientFactory.java View source code
protected Client createClient(String targetIP, int targetPort, int connectTimeout, String key) throws Exception {
    final Netty4ClientHandler handler = new Netty4ClientHandler(this, key);
    EventLoopGroup group = new NioEventLoopGroup(1);
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true"))).option(ChannelOption.SO_REUSEADDR, Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true"))).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout < 1000 ? 1000 : connectTimeout).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("decoder", new Netty4ProtocolDecoder());
            ch.pipeline().addLast("encoder", new Netty4ProtocolEncoder());
            ch.pipeline().addLast("handler", handler);
        }
    });
    ChannelFuture future = b.connect(targetIP, targetPort);
    future.awaitUninterruptibly(connectTimeout);
    if (!future.isDone()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " timeout!");
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " timeout!");
    }
    if (future.isCancelled()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " cancelled by user!");
    }
    if (!future.isSuccess()) {
        LOGGER.error("Create connection to " + targetIP + ":" + targetPort + " error", future.cause());
        throw new Exception("Create connection to " + targetIP + ":" + targetPort + " error", future.cause());
    }
    Netty4Client client = new Netty4Client(future, key, connectTimeout);
    handler.setClient(client);
    return client;
}
Example 64
Project: onos-master  File: OFConnectionHandler.java View source code
/**
     * Creates a connection to the supplied controller.
     */
public void connect() {
    SocketAddress remoteAddr = new InetSocketAddress(controller.ip().toInetAddress(), controller.port().toInt());
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true).handler(new OFChannelInitializer(ofSwitch));
    log.debug(String.format(MSG_STATE, ofSwitch.dpid(), MSG_CONNECTING, controller.ip(), controller.port()));
    bootstrap.connect(remoteAddr).addListener(this);
}
Example 65
Project: openflowjava-master  File: SimpleClient.java View source code
/**
     * Starting class of {@link SimpleClient}
     */
@Override
public void run() {
    group = new NioEventLoopGroup();
    SimpleClientInitializer clientInitializer = new SimpleClientInitializer(isOnlineFuture, securedClient);
    clientInitializer.setScenario(scenarioHandler);
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(clientInitializer);
        b.connect(host, port).sync();
        synchronized (scenarioHandler) {
            LOG.debug("WAITING FOR SCENARIO");
            while (!scenarioHandler.isScenarioFinished()) {
                scenarioHandler.wait();
            }
        }
    } catch (Exception ex) {
        LOG.error(ex.getMessage(), ex);
    } finally {
        LOG.debug("shutting down");
        try {
            group.shutdownGracefully().get();
            LOG.debug("shutdown succesful");
        } catch (InterruptedExceptionExecutionException |  e) {
            LOG.error(e.getMessage(), e);
        }
    }
    scenarioDone.set(true);
}
Example 66
Project: remote-netty-master  File: AbstractClientConfigure.java View source code
@Override
public void init() throws Exception {
    if (isStarted.get()) {
        throw new IllegalStateException("Netty client bootstrap already started!");
    }
    configure();
    if (channelInitializer == null) {
        throw new IllegalStateException("ChannelInitializer is null, unset in configure() ?");
    }
    if (!bossGroupSetted) {
        bossGroup = EventLoopGroupFactory.newNioLoopGroup(bossGroupSize);
    }
    bootstrap = new Bootstrap();
    bootstrap.group(bossGroup).channel(NioSocketChannel.class).handler(channelInitializer);
    options(bootstrap);
    isStarted.set(true);
    isShutdown.set(false);
    log.info(String.format("Netty client started with properties -> [BossGroupSize=%1$d]", bossGroup.executorCount()));
}
Example 67
Project: Resteasy-master  File: RESTEASY1325Test.java View source code
/**
     * Test case
     * @throws InterruptedException
     * @throws MalformedURLException
     */
private void callAndIdle() throws InterruptedException, MalformedURLException {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(new HttpClientCodec());
                ch.pipeline().addLast(new HttpObjectAggregator(4096));
                ch.pipeline().addLast(new SimpleChannelInboundHandler<FullHttpResponse>() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) {
                        System.out.println("HTTP response from resteasy: " + msg);
                        Assert.assertEquals(HttpResponseStatus.OK, msg.getStatus());
                    }
                });
            }
        });
        // first request;
        URL url = new URL(BASE_URI + "/test");
        // Make the connection attempt.
        final Channel ch = b.connect(url.getHost(), url.getPort()).sync().channel();
        // Prepare the HTTP request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, url.getFile());
        request.headers().set(HttpHeaderNames.HOST, url.getHost());
        request.headers().set(HttpHeaderNames.CONNECTION, "keep-alive");
        // Send the HTTP request.
        ch.writeAndFlush(request);
        // waiting for server close connection after idle.
        ch.closeFuture().await();
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
    }
}
Example 68
Project: RipplePower-master  File: MessageClient.java View source code
public void init(String username, JTextArea messageShow, String ip, int port, RPComboBox combobox) throws Exception {
    this.messageShow = messageShow;
    this.username = username;
    this.combobox = combobox;
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(new ByteMesDecoder(new MessageRecognizer())).addLast(new MesToByteEncoder());
            pipeline.addLast("LOGGING_HANDLER", LOGGING_HANDLER);
            pipeline.addLast(new GameClientHandler());
        }
    });
    ChannelFuture f = b.connect(ip, port).sync();
    this.channel = f.channel();
    LoginMessage msg = new LoginMessage(username);
    channel.writeAndFlush(msg);
    channel.closeFuture().sync();
}
Example 69
Project: sdk-dslink-java-master  File: DefaultHttpProvider.java View source code
@Override
public HttpResp post(URLInfo url, byte[] content, Map<String, String> headers) {
    if (url == null) {
        throw new NullPointerException("url");
    }
    try {
        final HttpHandler handler = new HttpHandler();
        Bootstrap b = new Bootstrap();
        b.group(SharedObjects.getLoop());
        b.channel(NioSocketChannel.class);
        b.handler(new Initializer(handler, url.secure));
        ChannelFuture fut = b.connect(url.host, url.port);
        Channel chan = fut.sync().channel();
        chan.writeAndFlush(populateRequest(url.path, content, headers));
        fut.channel().closeFuture().sync();
        return populateResponse(handler);
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}
Example 70
Project: spray-cache-spymemcached-master  File: PeriodicConfigRetrievalClient.java View source code
public static ChannelFuture configureBootstrap(ElastiCacheConfigServerChooser configServerService, final ClientInfoClientHandler handler, Bootstrap b, EventLoopGroup g, final TimeUnit idleTimeoutTimeUnit, final long idleTimeout, final int connectionTimeoutInMillis) {
    final ElastiCacheServerConnectionDetails configServer = configServerService.getServer();
    b.group(g).channel(NioSocketChannel.class).remoteAddress(configServer.getHost(), configServer.getPort()).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.config().setConnectTimeoutMillis(connectionTimeoutInMillis);
            ch.pipeline().addLast(new ConfigInfoDecoder());
            ch.pipeline().addLast(new IdleStateHandler(idleTimeout, 0, 0, idleTimeoutTimeUnit));
            ch.pipeline().addLast(handler);
        }
    });
    return b.connect().addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.cause() != null) {
                log.warn("Failed to connect: {}:{}", configServer.getHost(), configServer.getPort(), future.cause());
            }
        }
    });
}
Example 71
Project: tesora-dve-pub-master  File: MysqlClientHandler.java View source code
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    final Channel inboundChannel = ctx.channel();
    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class).handler(new LoadBalancerServerHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false);
    ChannelFuture f = b.connect(peServerAddress);
    outboundChannel = f.channel();
    f.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();
            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });
}
Example 72
Project: vethrfolnir-mu-master  File: LoginServerClient.java View source code
@Inject
private void load() {
    log.info("Preparing To connect to login! Info[Host: " + host + ", Port: " + port + "]");
    try {
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(workerGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(//new LoggingHandler(LogLevel.INFO)
                new LoginServerClientHandler(LoginServerClient.this));
            }
        });
    } catch (Exception e) {
        log.fatal("Unable to set up netty!", e);
    }
}
Example 73
Project: WaarpCommon-master  File: WaarpNettyUtil.java View source code
/**
     * Add default configuration for client bootstrap
     * 
     * @param bootstrap
     * @param group
     * @param timeout
     */
public static void setBootstrap(Bootstrap bootstrap, EventLoopGroup group, int timeout) {
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.group(group);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout);
    bootstrap.option(ChannelOption.SO_RCVBUF, 1048576);
    bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
    bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 10 * 65536);
    bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 2 * 65536);
    bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
}
Example 74
Project: zava-master  File: SnNettyRpcConnection.java View source code
public SnRpcResponse sendRequest(final SnRpcRequest request) throws Throwable {
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(workerGroup// (2)
        );
        b.channel(// (3)
        NioSocketChannel.class);
        // (4)
        b.option(// (4)
        ChannelOption.SO_KEEPALIVE, // (4)
        true);
        b.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                //�次处�连接信�SnNettyRpcConnection,Request编�,Response解�
                ch.pipeline().addLast(new SnRpcResponseDecoder());
                ch.pipeline().addLast(new SnRpcRequestEncoder());
                ch.pipeline().addLast(SnNettyRpcConnection.this);
            }
        });
        Channel ch = b.connect(inetAddr).sync().channel();
        //��rpc调用请求
        ch.writeAndFlush(request);
        //等待收到rpc调用结果
        waitForResponse();
        //执行到这里一定是收到了�务端的�应
        SnRpcResponse resp = this.response;
        if (resp != null) {
            ch.closeFuture().sync();
        }
        return resp;
    } finally {
        workerGroup.shutdownGracefully();
    }
}
Example 75
Project: AgentX-master  File: XConnectHandler.java View source code
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    try {
        ByteBuf byteBuf = (ByteBuf) msg;
        if (!byteBuf.hasArray()) {
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.getBytes(0, bytes);
            if (!requestParsed) {
                if (!exposedRequest) {
                    bytes = wrapper.unwrap(bytes);
                    if (bytes == null) {
                        log.info("\tClient -> Proxy           \tHalf Request");
                        return;
                    }
                }
                XRequest xRequest = requestWrapper.parse(bytes);
                String host = xRequest.getHost();
                int port = xRequest.getPort();
                int dataLength = xRequest.getSubsequentDataLength();
                if (dataLength > 0) {
                    byte[] tailData = Arrays.copyOfRange(bytes, bytes.length - dataLength, bytes.length);
                    if (exposedRequest) {
                        tailData = wrapper.unwrap(tailData);
                        if (tailData != null) {
                            tailDataBuffer.write(tailData, 0, tailData.length);
                        }
                    } else {
                        tailDataBuffer.write(tailData, 0, tailData.length);
                    }
                }
                log.info("\tClient -> Proxy           \tTarget {}:{}{}", host, port, DnsCache.isCached(host) ? " [Cached]" : "");
                if (xRequest.getAtyp() == XRequest.Type.DOMAIN) {
                    try {
                        host = DnsCache.get(host);
                        if (host == null) {
                            host = xRequest.getHost();
                        }
                    } catch (UnknownHostException e) {
                        log.warn("\tClient <- Proxy           \tBad DNS! ({})", e.getMessage());
                        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                        return;
                    }
                }
                Promise<Channel> promise = ctx.executor().newPromise();
                promise.addListener(new FutureListener<Channel>() {

                    @Override
                    public void operationComplete(final Future<Channel> future) throws Exception {
                        final Channel outboundChannel = future.getNow();
                        if (future.isSuccess()) {
                            // handle tail
                            byte[] tailData = tailDataBuffer.toByteArray();
                            tailDataBuffer.close();
                            if (tailData.length > 0) {
                                log.info("\tClient ==========> Target \tSend Tail [{} bytes]", tailData.length);
                            }
                            outboundChannel.writeAndFlush((tailData.length > 0) ? Unpooled.wrappedBuffer(tailData) : Unpooled.EMPTY_BUFFER).addListener( channelFuture -> {
                                outboundChannel.pipeline().addLast(new XRelayHandler(ctx.channel(), wrapper, false));
                                ctx.pipeline().addLast(new XRelayHandler(outboundChannel, wrapper, true));
                                ctx.pipeline().remove(XConnectHandler.this);
                            });
                        } else {
                            if (ctx.channel().isActive()) {
                                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                            }
                        }
                    }
                });
                final String finalHost = host;
                bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true).handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port).addListener(new ChannelFutureListener() {

                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (!future.isSuccess()) {
                            if (ctx.channel().isActive()) {
                                log.warn("\tClient <- Proxy           \tBad Ping! ({}:{})", finalHost, port);
                                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                            }
                        }
                    }
                });
                requestParsed = true;
            } else {
                bytes = wrapper.unwrap(bytes);
                if (bytes != null)
                    tailDataBuffer.write(bytes, 0, bytes.length);
            }
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}
Example 76
Project: Ak47-master  File: NettySimpleDriver.java View source code
private void initBootstrap() {
    final NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    bootstrap = new Bootstrap();
    bootstrap.group(workerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_RCVBUF, Ak47Constants.SO_RCVBUF).option(ChannelOption.SO_SNDBUF, Ak47Constants.SO_SNDBUF).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            NettyChannel<Q, R> channel = new NettyChannel<Q, R>(ch);
            channel.chain().addLast("StubInitializer", stubInitializer);
            if (userInitializer != null) {
                channel.chain().addLast("UserInitializer", userInitializer);
            }
            NettyChannelHandlerAdapter<Q, R> nettyChannelHandler = new NettyChannelHandlerAdapter<Q, R>(channel, pipe, pipe.newExecutor());
            ch.pipeline().addLast("NettyChannelHandlerAdapter", nettyChannelHandler);
        }
    });
    log.debug("Driver init success.");
}
Example 77
Project: Android-wamp-client-master  File: WampClientChannelFactoryResolver.java View source code
@Override
public ChannelFuture createChannel(final ChannelHandler handler, final EventLoopGroup eventLoop, final ObjectMapper objectMapper) throws Exception {
    // Initialize SSL when required
    final boolean needSsl = uri.getScheme().equalsIgnoreCase("wss");
    final SslContext sslCtx0;
    if (needSsl && sslCtx == null) {
        // Create a default SslContext when we got none provided through the constructor
        try {
            sslCtx0 = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
        } catch (SSLException e) {
            throw e;
        }
    } else if (needSsl) {
        sslCtx0 = sslCtx;
    } else {
        sslCtx0 = null;
    }
    // Use well-known ports if not explicitly specified
    final int port;
    if (uri.getPort() == -1) {
        if (needSsl)
            port = 443;
        else
            port = 80;
    } else
        port = uri.getPort();
    final WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, WampHandlerConfiguration.WAMP_WEBSOCKET_PROTOCOLS, false, new DefaultHttpHeaders());
    Bootstrap b = new Bootstrap();
    b.group(eventLoop).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) {
            ChannelPipeline p = ch.pipeline();
            if (sslCtx0 != null) {
                p.addLast(sslCtx0.newHandler(ch.alloc(), uri.getHost(), port));
            }
            p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), new WebSocketClientProtocolHandler(handshaker, false), new WebSocketFrameAggregator(WampHandlerConfiguration.MAX_WEBSOCKET_FRAME_SIZE), new WampClientWebsocketHandler(handshaker, objectMapper), handler);
        }
    });
    return b.connect(uri.getHost(), port);
}
Example 78
Project: ari4java-master  File: TestNettyHttp.java View source code
public static void main(String[] args) {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        URI uri = new URI("http://192.168.0.194:8088/");
        Bootstrap b = new Bootstrap();
        String protocol = uri.getScheme();
        if (!"http".equals(protocol)) {
            throw new IllegalArgumentException("Unsupported protocol: " + protocol);
        }
        final HttpClientHandler handler = new HttpClientHandler();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("http-codec", new HttpClientCodec());
                pipeline.addLast("aggregator", new HttpObjectAggregator(8192));
                pipeline.addLast("http-handler", handler);
            }
        });
        System.out.println("HTTP Client connecting");
        Channel ch = b.connect(uri.getHost(), uri.getPort()).sync().channel();
        HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/ari/asterisk/info?api_key=admin:admin");
        request.headers().set(HttpHeaders.Names.HOST, "localhost");
        request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
        ch.writeAndFlush(request);
        ch.closeFuture().sync();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        group.shutdownGracefully();
    }
}
Example 79
Project: blynk-server-master  File: BaseClient.java View source code
public void start(BufferedReader commandInputStream) {
    this.nioEventLoopGroup = new NioEventLoopGroup(1);
    try {
        Bootstrap b = new Bootstrap();
        b.group(nioEventLoopGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true).handler(getChannelInitializer());
        // Start the connection attempt.
        this.channel = b.connect(host, port).sync().channel();
        readUserInput(commandInputStream);
    } catch (UnresolvedAddressException uae) {
        log.error("Host name '{}' is invalid. Please make sure it is correct name.", host);
    } catch (ConnectTimeoutException cte) {
        log.error("Timeout exceeded when connecting to '{}:{}'. Please make sure host available and port is open on target host.", host, port);
    } catch (IOExceptionInterruptedException |  e) {
        log.error("Error running client. Shutting down.", e);
    } catch (Exception e) {
        log.error(e);
    } finally {
        // The connection is closed automatically on shutdown.
        nioEventLoopGroup.shutdownGracefully();
    }
}
Example 80
Project: cassandra-connector-java-master  File: CassandraDriver.java View source code
public CassandraConnection newConnection(InetSocketAddress socketAddress, CassandraOptions options) {
    if (isShutdown()) {
        throw new IllegalStateException("driver shutdown");
    }
    Channel channel = new NioSocketChannel();
    channel.pipeline().addLast(tracer);
    if (options.getSslContext() != null) {
        SSLEngine engine = options.getSslContext().createSSLEngine();
        engine.setUseClientMode(true);
        if (options.getCipherSuites() != null) {
            engine.setEnabledCipherSuites(options.getCipherSuites());
        }
        channel.pipeline().addLast(new SslHandler(engine));
    }
    channel.pipeline().addLast(new CassandraMessageCodec(options.getCompression()));
    channel.pipeline().addLast(handler);
    channel.config().setOption(ChannelOption.SO_KEEPALIVE, true);
    channel.config().setOption(ChannelOption.TCP_NODELAY, true);
    channel.config().setOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.getConnectTimeoutMillis());
    ChannelFuture registerFuture = worker.register(channel);
    if (registerFuture.cause() != null) {
        if (channel.isRegistered()) {
            channel.close();
        } else {
            channel.unsafe().closeForcibly();
        }
        throw new IllegalStateException(registerFuture.cause().getMessage());
    }
    return new CassandraConnection(options, futureMap, channel, socketAddress);
}
Example 81
Project: catalyst-master  File: NettyClient.java View source code
@Override
public CompletableFuture<Connection> connect(Address address) {
    Assert.notNull(address, "address");
    ThreadContext context = ThreadContext.currentContextOrThrow();
    CompletableFuture<Connection> future = new ComposableFuture<>();
    LOGGER.info("Connecting to {}", address);
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(transport.eventLoopGroup()).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            if (transport.properties().sslEnabled()) {
                pipeline.addFirst(new SslHandler(new NettyTls(transport.properties()).initSslEngine(true)));
            }
            pipeline.addLast(FIELD_PREPENDER);
            pipeline.addLast(new LengthFieldBasedFrameDecoder(transport.properties().maxFrameSize(), 0, 4, 0, 4));
            pipeline.addLast(new NettyHandler(connections, future::complete, context, transport.properties()));
        }
    });
    bootstrap.option(ChannelOption.TCP_NODELAY, transport.properties().tcpNoDelay());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, transport.properties().tcpKeepAlive());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, transport.properties().connectTimeout());
    bootstrap.option(ChannelOption.ALLOCATOR, ALLOCATOR);
    if (transport.properties().sendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, transport.properties().sendBufferSize());
    }
    if (transport.properties().receiveBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_RCVBUF, transport.properties().receiveBufferSize());
    }
    bootstrap.connect(address.socketAddress()).addListener( channelFuture -> {
        if (channelFuture.isSuccess()) {
            LOGGER.info("Connected to {}", address);
        } else {
            context.execute(() -> future.completeExceptionally(channelFuture.cause()));
        }
    });
    return future;
}
Example 82
Project: Chronicle-Network-master  File: NettyClientThroughPutTest.java View source code
public static void main(String[] args) throws SSLException, InterruptedException {
    // Configure SSL.git
    @Nullable final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }
    // Configure the client.
    @NotNull EventLoopGroup group = new NioEventLoopGroup();
    try {
        @NotNull Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(@NotNull SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                }
                //p.addLast(new LoggingHandler(LogLevel.INFO));
                p.addLast(new MyChannelInboundHandler());
            }
        });
        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT).sync();
        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}
Example 83
Project: dcache-master  File: NettyLineBasedDoorFactory.java View source code
@Override
public Cell newCell(Socket socket) throws InvocationTargetException {
    NettyLineBasedDoor door = new NettyLineBasedDoor(parentCellName + "*", args, factory, executor, poolManagerHandler);
    NioSocketChannel channel = new NioSocketChannel(socket.getChannel());
    ChannelPipeline pipeline = channel.pipeline();
    pipeline.addLast("door", door);
    socketGroup.register(channel);
    return door;
}
Example 84
Project: examples-javafx-repos1-master  File: EchoClientController.java View source code
@Override
protected Channel call() throws Exception {
    updateMessage("Bootstrapping");
    updateProgress(0.1d, 1.0d);
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class).remoteAddress(new InetSocketAddress(host, port)).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new EchoClientHandler(receivingMessageModel));
        }
    });
    ChannelFuture f = b.connect();
    Channel chn = f.channel();
    updateMessage("Connecting");
    updateProgress(0.2d, 1.0d);
    f.sync();
    return chn;
}
Example 85
Project: floodlight-master  File: BootstrapClient.java View source code
public void init() throws SyncException {
    cg = new DefaultChannelGroup("Cluster Bootstrap", GlobalEventExecutor.INSTANCE);
    workerExecutor = new NioEventLoopGroup();
    timer = new HashedWheelTimer();
    bootstrap = new Bootstrap().group(workerExecutor).channel(NioSocketChannel.class).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_SNDBUF, RPCService.SEND_BUFFER_SIZE).option(ChannelOption.SO_RCVBUF, RPCService.SEND_BUFFER_SIZE).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, RPCService.CONNECT_TIMEOUT);
    pipelineFactory = new BootstrapChannelInitializer(timer, this);
    bootstrap.handler(pipelineFactory);
}
Example 86
Project: Framework-GL-master  File: Network.java View source code
private void createClient(String host, int port, Supplier<ChannelHandler> channelHandlerSupplier) {
    // Create event loops
    clientWorkerGroup = new NioEventLoopGroup();
    // Create channel initializer
    ChannelInitializer<SocketChannel> channelInit = new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            if (debug) {
                p.addLast(new LoggingHandler(logLevel));
            }
            p.addLast(channelHandlerSupplier.get());
        }
    };
    // Bootstrap the client
    client = new Bootstrap();
    if (debug) {
        client.handler(new LoggingHandler(logLevel));
    }
    client.group(clientWorkerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, keepAlive).option(ChannelOption.TCP_NODELAY, tcpNoDelay).handler(channelInit);
    // Connect to the host and port
    client.connect(host, port);
}
Example 87
Project: gelfclient-master  File: GelfTcpTransport.java View source code
@Override
protected void createBootstrap(final EventLoopGroup workerGroup) {
    final Bootstrap bootstrap = new Bootstrap();
    final GelfSenderThread senderThread = new GelfSenderThread(queue, config.getMaxInflightSends());
    bootstrap.group(workerGroup).channel(NioSocketChannel.class).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout()).option(ChannelOption.TCP_NODELAY, config.isTcpNoDelay()).option(ChannelOption.SO_KEEPALIVE, config.isTcpKeepAlive()).remoteAddress(config.getRemoteAddress()).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            if (config.isTlsEnabled()) {
                LOG.debug("TLS enabled.");
                final SslContext sslContext;
                if (!config.isTlsCertVerificationEnabled()) {
                    // If the cert should not be verified just use an insecure trust manager.
                    LOG.debug("TLS certificate verification disabled!");
                    sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
                } else if (config.getTlsTrustCertChainFile() != null) {
                    // If a cert chain file is set, use it.
                    LOG.debug("TLS certificate chain file: {}", config.getTlsTrustCertChainFile());
                    sslContext = SslContextBuilder.forClient().trustManager(config.getTlsTrustCertChainFile()).build();
                } else {
                    // Otherwise use the JVM default cert chain.
                    sslContext = SslContextBuilder.forClient().build();
                }
                ch.pipeline().addLast(sslContext.newHandler(ch.alloc()));
            }
            // The graylog2-server uses '\0'-bytes as delimiter for TCP frames.
            ch.pipeline().addLast(new GelfTcpFrameDelimiterEncoder());
            // We cannot use GZIP encoding for TCP because the headers contain '\0'-bytes then.
            ch.pipeline().addLast(new GelfMessageJsonEncoder());
            ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() {

                @Override
                protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
                // We do not receive data.
                }

                @Override
                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                    senderThread.start(ctx.channel());
                }

                @Override
                public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                    LOG.info("Channel disconnected!");
                    senderThread.stop();
                    scheduleReconnect(ctx.channel().eventLoop());
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    LOG.error("Exception caught", cause);
                }
            });
        }
    });
    if (config.getSendBufferSize() != -1) {
        bootstrap.option(ChannelOption.SO_SNDBUF, config.getSendBufferSize());
    }
    bootstrap.connect().addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                LOG.debug("Connected!");
            } else {
                LOG.error("Connection failed: {}", future.cause().getMessage());
                scheduleReconnect(future.channel().eventLoop());
            }
        }
    });
}
Example 88
Project: hadoop-master  File: TestDtpHttp2.java View source code
@BeforeClass
public static void setUp() throws IOException, URISyntaxException, TimeoutException {
    CLUSTER = new MiniDFSCluster.Builder(CONF).numDataNodes(1).build();
    CLUSTER.waitActive();
    RESPONSE_HANDLER = new Http2ResponseHandler();
    Bootstrap bootstrap = new Bootstrap().group(WORKER_GROUP).channel(NioSocketChannel.class).remoteAddress("127.0.0.1", CLUSTER.getDataNodes().get(0).getInfoPort()).handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            Http2Connection connection = new DefaultHttp2Connection(false);
            Http2ConnectionHandler connectionHandler = new HttpToHttp2ConnectionHandler(connection, frameReader(), frameWriter(), new DelegatingDecompressorFrameListener(connection, new InboundHttp2ToHttpAdapter.Builder(connection).maxContentLength(Integer.MAX_VALUE).propagateSettings(true).build()));
            ch.pipeline().addLast(connectionHandler, RESPONSE_HANDLER);
        }
    });
    CHANNEL = bootstrap.connect().syncUninterruptibly().channel();
}
Example 89
Project: hadoop-release-2.6.0-master  File: SimpleHttpProxyHandler.java View source code
@Override
public void channelRead0(final ChannelHandlerContext ctx, final HttpRequest req) {
    uri = req.getUri();
    final Channel client = ctx.channel();
    Bootstrap proxiedServer = new Bootstrap().group(client.eventLoop()).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(new HttpRequestEncoder(), new Forwarder(uri, client));
        }
    });
    ChannelFuture f = proxiedServer.connect(host);
    proxiedChannel = f.channel();
    f.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                ctx.channel().pipeline().remove(HttpResponseEncoder.class);
                HttpRequest newReq = new DefaultFullHttpRequest(HTTP_1_1, req.getMethod(), req.getUri());
                newReq.headers().add(req.headers());
                newReq.headers().set(CONNECTION, Values.CLOSE);
                future.channel().writeAndFlush(newReq);
            } else {
                DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR);
                resp.headers().set(CONNECTION, Values.CLOSE);
                LOG.info("Proxy " + uri + " failed. Cause: ", future.cause());
                ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
                client.close();
            }
        }
    });
}
Example 90
Project: infinispan-master  File: HotRodPipeTest.java View source code
void start() {
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(new BatchingDecoder());
            p.addLast(new BatchingEncoder());
            p.addLast(new BatchingClientHandler());
        }
    });
    try {
        ChannelFuture f = b.connect(host(), port).sync();
        ch = f.channel();
    } catch (InterruptedException e) {
        throw new AssertionError(e);
    }
}
Example 91
Project: intellij-community-master  File: SimpleProtobufClient.java View source code
public final boolean connect(final String host, final int port) throws Throwable {
    if (myState.compareAndSet(State.DISCONNECTED, State.CONNECTING)) {
        boolean success = false;
        try {
            final Bootstrap bootstrap = new Bootstrap().group(myEventLoopGroup).channel(NioSocketChannel.class).handler(myChannelInitializer);
            bootstrap.option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true);
            final ChannelFuture future = bootstrap.connect(host, port).syncUninterruptibly();
            success = future.isSuccess();
            if (success) {
                myConnectFuture = future;
                try {
                    onConnect();
                } catch (Throwable e) {
                    LOG.error(e);
                }
            }
            return success;
        } finally {
            myState.compareAndSet(State.CONNECTING, success ? State.CONNECTED : State.DISCONNECTED);
        }
    }
    // already connected
    return true;
}
Example 92
Project: jfxvnc-master  File: VncConnection.java View source code
public CompletableFuture<VncConnection> connect() {
    shutdown();
    CompletableFuture<VncConnection> future = new CompletableFuture<>();
    workerGroup = new NioEventLoopGroup(2, executor);
    connecting.set(true);
    String host = config.hostProperty().get();
    int port = config.portProperty().get() > 0 ? config.portProperty().get() : DEF_CONNECT_PORT;
    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
    b.handler(new ProtocolInitializer(render, config));
    logger.debug("try to connect to {}:{}", host, port);
    b.connect(host, port).addListener((ChannelFuture in) -> {
        connecting.set(false);
        connected.set(in.isSuccess());
        if (!in.isSuccess()) {
            future.completeExceptionally(in.cause());
            return;
        }
        future.complete(this);
    });
    return future;
}
Example 93
Project: jlibs-master  File: NettyClientEndpoint.java View source code
@Override
public void connect(final URI uri, final ConnectListener listener, final String... subProtocols) {
    final SslContext sslContext;
    if ("wss".equals(uri.getScheme())) {
        try {
            if (sslSettings == null) {
                sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
            } else {
                sslContext = SslContextBuilder.forClient().trustManager(sslSettings.trustCertChainFile).keyManager(sslSettings.certificateFile, sslSettings.keyFile, sslSettings.keyPassword).build();
            }
        } catch (Throwable thr) {
            listener.onError(thr);
            return;
        }
    } else if ("ws".equals(uri.getScheme()))
        sslContext = null;
    else
        throw new IllegalArgumentException("invalid protocol: " + uri.getScheme());
    final int port = uri.getPort() == -1 ? (sslContext == null ? 80 : 443) : uri.getPort();
    Bootstrap bootstrap = new Bootstrap().group(eventLoopGroup).channel(NioSocketChannel.class).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).option(ChannelOption.MAX_MESSAGES_PER_READ, 50000).option(ChannelOption.WRITE_SPIN_COUNT, 50000).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            if (sslContext != null)
                ch.pipeline().addLast(sslContext.newHandler(ch.alloc(), uri.getHost(), port));
            WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, Util.toString(subProtocols), false, new DefaultHttpHeaders());
            ch.pipeline().addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), new WebSocketClientProtocolHandler(handshaker) {

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    super.exceptionCaught(ctx, cause);
                    listener.onError(cause);
                }
            }, new HandshakeListener(handshaker, listener));
        }
    });
    bootstrap.connect(uri.getHost(), port).addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                assert !future.channel().isOpen();
                listener.onError(future.cause());
            }
        }
    });
}
Example 94
Project: jreactive-8583-master  File: Iso8583Client.java View source code
@Override
protected Bootstrap createBootstrap() {
    final Bootstrap b = new Bootstrap();
    b.group(getBossEventLoopGroup()).channel(NioSocketChannel.class).remoteAddress(getSocketAddress()).handler(new Iso8583ChannelInitializer<>(getConfiguration(), getConfigurer(), getWorkerEventLoopGroup(), getIsoMessageFactory(), getMessageHandler()));
    configureBootstrap(b);
    b.validate();
    reconnectOnCloseListener = new ReconnectOnCloseListener(this, getConfiguration().getReconnectInterval(), getBossEventLoopGroup());
    return b;
}
Example 95
Project: kume-master  File: NettyTransport.java View source code
@Override
public MemberChannel connect(Member member) throws InterruptedException {
    Bootstrap b = new Bootstrap();
    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.group(workerGroup).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
            p.addLast("packetDecoder", new PacketDecoder());
            p.addLast("frameEncoder", new LengthFieldPrepender(4));
            p.addLast("packetEncoder", new PacketEncoder());
            p.addLast("server", new ClientChannelAdapter(messageHandlers));
        }
    });
    ChannelFuture f = b.connect(member.getAddress()).sync().addListener( future -> {
        if (!future.isSuccess()) {
            LOGGER.error("Failed to connect server {}", member.getAddress());
        }
    }).sync();
    return new NettyChannel(f.channel());
}
Example 96
Project: light-task-scheduler-master  File: NettyRemotingClient.java View source code
@Override
protected void clientStart() throws RemotingException {
    NettyLogger.setNettyLoggerFactory();
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(remotingClientConfig.getClientWorkerThreads(), new NamedThreadFactory("NettyClientWorkerThread_"));
    final NettyCodecFactory nettyCodecFactory = new NettyCodecFactory(appContext, getCodec());
    this.bootstrap.group(this.eventLoopGroup).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(defaultEventExecutorGroup, nettyCodecFactory.getEncoder(), nettyCodecFactory.getDecoder(), //
            new IdleStateHandler(remotingClientConfig.getReaderIdleTimeSeconds(), remotingClientConfig.getWriterIdleTimeSeconds(), remotingClientConfig.getClientChannelMaxIdleTimeSeconds()), new NettyConnectManageHandler(), new NettyClientHandler());
        }
    });
}
Example 97
Project: LittleProxy-mitm-master  File: RetryClient.java View source code
private void connect(final boolean retry, EventLoopGroup loop) throws InterruptedException {
    Bootstrap b = new Bootstrap();
    b.group(loop);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) {
            ChannelPipeline p = ch.pipeline();
            if (sslCtx != null) {
                if (retry) {
                    p.addLast(sslCtx.newHandler(ch.alloc()));
                } else {
                    p.addLast(sslCtx.newHandler(ch.alloc(), uri.getHost(), uri.getPort()));
                }
            }
            p.addLast(new HttpClientCodec());
            p.addLast(new RetryClientHandler(RetryClient.this));
        }
    });
    Channel ch = b.connect(uri.getHost(), uri.getPort()).sync().channel();
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString());
    request.headers().set(HttpHeaders.Names.HOST, uri.getHost());
    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    ch.writeAndFlush(request);
    ch.closeFuture().sync();
}
Example 98
Project: mpush-master  File: ConnClientBoot.java View source code
@Override
protected void doStart(Listener listener) throws Throwable {
    ServiceDiscoveryFactory.create().syncStart();
    CacheManagerFactory.create().init();
    this.workerGroup = new NioEventLoopGroup();
    this.bootstrap = new Bootstrap();
    //
    bootstrap.group(workerGroup).option(ChannelOption.TCP_NODELAY, //
    true).option(ChannelOption.SO_REUSEADDR, //
    true).option(ChannelOption.ALLOCATOR, //
    PooledByteBufAllocator.DEFAULT).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 60 * 1000).option(ChannelOption.SO_RCVBUF, 5 * 1024 * 1024).channel(NioSocketChannel.class);
    bootstrap.handler(new // (4)
    ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("decoder", new PacketDecoder());
            ch.pipeline().addLast("encoder", PacketEncoder.INSTANCE);
            ch.pipeline().addLast("handler", new ConnClientChannelHandler());
        }
    });
    listener.onSuccess();
}
Example 99
Project: mvn-dev-proxy-master  File: HttpFrontEndHandler.java View source code
private void handleProxyRequest(final ChannelHandlerContext ctx, final FullHttpRequest msg) {
    final Channel inboundChannel = ctx.channel();
    // Start the connection attempt.
    Bootstrap b = new Bootstrap();
    ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(new HttpClientCodec());
            // Remove the following line if you don't want automatic content decompression.
            //p.addLast(new HttpContentDecompressor());
            p.addLast(new HttpObjectAggregator(1048576));
            p.addLast(new HttpBackEndHandler(inboundChannel));
        }
    };
    b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class).handler(initializer);
    // Make the connection attempt.
    if (channelFuture == null || (channelFuture.isSuccess() && !channelFuture.channel().isOpen())) {
        logger.debug("Instantiating new connection");
        channelFuture = b.connect(host, port);
    } else {
        logger.debug("Reusing connection");
    }
    channelFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Prepare the HTTP request.
                HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, msg.getMethod(), msg.getUri());
                request.headers().add(msg.headers());
                request.headers().set(HttpHeaders.Names.HOST, host);
                //request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
                //request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
                future.channel().writeAndFlush(request);
            } else {
                logger.info("Connection issue", future.cause());
                sendError(ctx, HttpResponseStatus.BAD_GATEWAY);
            }
        }
    });
}
Example 100
Project: netty-zmtp-master  File: ProtocolViolationTests.java View source code
@Before
public void setup() {
    final ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.channel(NioServerSocketChannel.class);
    bossGroup = new NioEventLoopGroup(1);
    group = new NioEventLoopGroup();
    serverBootstrap.group(bossGroup, group);
    serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {

        @Override
        protected void initChannel(final NioSocketChannel ch) throws Exception {
            ch.pipeline().addLast(ZMTPCodec.builder().protocol(ZMTP20).socketType(ROUTER).localIdentity(identity).build(), mockHandler);
        }
    });
    serverChannel = serverBootstrap.bind(new InetSocketAddress("localhost", 0)).awaitUninterruptibly().channel();
    serverAddress = (InetSocketAddress) serverChannel.localAddress();
}
Example 101
Project: NettyAndroid-master  File: Client.java View source code
public void InitializationWithWorkThread() {
    if (socketChannel != null && socketChannel.isOpen() && socketChannel.isActive()) {
        logger.info("socket 已�建立了链接");
        return;
    }
    onDestrOY = false;
    if (host == null || port == 0) {
        return;
    }
    Bootstrap bootstrap = new Bootstrap();
    NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    try {
        bootstrap.channel(NioSocketChannel.class).group(eventLoopGroup).option(ChannelOption.SO_KEEPALIVE, true).remoteAddress(host, port).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new IdleStateHandler(60, 60, 90));
                ch.pipeline().addLast(new EncodeHandler());
                ch.pipeline().addLast(new DecodeHandler());
                ch.pipeline().addLast(new CloseChannelHandler(Client.this));
                ch.pipeline().addLast(handler);
            }
        });
        ChannelFuture future = bootstrap.connect().sync();
        if (future.isSuccess()) {
            socketChannel = (SocketChannel) future.channel();
            logger.info("socketChannel连接�功");
        } else {
            throw new InterruptedException("connection fail.");
        }
    } catch (Exception e) {
        logger.info("socketChannel连接失败");
        logger.info(e);
        onDestroy();
        reset2Connect();
    }
}