Example usage for io.netty.channel.nio NioEventLoopGroup NioEventLoopGroup

List of usage examples for io.netty.channel.nio NioEventLoopGroup NioEventLoopGroup

Introduction

In this page you can find the example usage for io.netty.channel.nio NioEventLoopGroup NioEventLoopGroup.

Prototype

public NioEventLoopGroup() 

Source Link

Document

Create a new instance using the default number of threads, the default ThreadFactory and the SelectorProvider which is returned by SelectorProvider#provider() .

Usage

From source file:cf.dropsonde.firehose.NettyFirehoseOnSubscribe.java

License:Open Source License

public NettyFirehoseOnSubscribe(URI uri, String token, String subscriptionId, boolean skipTlsValidation,
        EventLoopGroup eventLoopGroup, Class<? extends SocketChannel> channelClass) {
    try {//from  w w w  .  jav  a2s  .  c  o  m
        final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
        final String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
        final int port = getPort(scheme, uri.getPort());
        final URI fullUri = uri.resolve("/firehose/" + subscriptionId);

        final SslContext sslContext;
        if ("wss".equalsIgnoreCase(scheme)) {
            final SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();
            if (skipTlsValidation) {
                sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
            } else {
                TrustManagerFactory trustManagerFactory = TrustManagerFactory
                        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                trustManagerFactory.init((KeyStore) null);
                sslContextBuilder.trustManager(trustManagerFactory);
            }
            sslContext = sslContextBuilder.build();
        } else {
            sslContext = null;
        }

        bootstrap = new Bootstrap();
        if (eventLoopGroup == null) {
            this.eventLoopGroup = new NioEventLoopGroup();
            bootstrap.group(this.eventLoopGroup);
        } else {
            this.eventLoopGroup = null;
            bootstrap.group(eventLoopGroup);
        }
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000)
                .channel(channelClass == null ? NioSocketChannel.class : channelClass).remoteAddress(host, port)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel c) throws Exception {
                        final HttpHeaders headers = new DefaultHttpHeaders();
                        headers.add(HttpHeaders.Names.AUTHORIZATION, token);
                        final WebSocketClientHandler handler = new WebSocketClientHandler(
                                WebSocketClientHandshakerFactory.newHandshaker(fullUri, WebSocketVersion.V13,
                                        null, false, headers));
                        final ChannelPipeline pipeline = c.pipeline();
                        if (sslContext != null) {
                            pipeline.addLast(sslContext.newHandler(c.alloc(), host, port));
                        }
                        pipeline.addLast(new ReadTimeoutHandler(30));
                        pipeline.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192));
                        pipeline.addLast(HANDLER_NAME, handler);

                        channel = c;
                    }
                });
    } catch (NoSuchAlgorithmException | SSLException | KeyStoreException e) {
        throw new RuntimeException(e);
    }
}

From source file:ch.ethz.globis.distindex.middleware.net.IndexMiddleware.java

License:Open Source License

@Override
public void run() {

    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();

    balancingDaemon.run();/*from   ww  w. j  av a 2  s.  c o  m*/
    try {
        //initialize the server channels
        ServerBootstrap b = initServerBootstrap(handler);
        ChannelFuture f = b.bind(port).sync();

        //register as a viable host to the cluster service
        clusterService.connect();
        if (joinedAsFree) {
            clusterService.registerFreeHost(getHostId());
        } else {
            clusterService.registerHost(getHostId());
        }
        isRunning = true;

        f.channel().closeFuture().sync();
    } catch (InterruptedException ie) {
        LOG.error("An error occurred while operating on the channel.", ie);
        ie.printStackTrace();
    } finally {
        closeEventLoops();
        isRunning = false;
        //disconnect the cluster service
        clusterService.disconnect();
    }
}

From source file:chapter01.EchoClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();

    try {/*from   ww  w .j a va2 s  .  c o m*/
        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 EchoClientHandler());
            }
        });

        ChannelFuture f = b.connect("localhost", 8888).sync();

        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:chapter10.WebSocketServer.java

License:Apache License

public void run(int port) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from   w  w w . j  a  v  a 2  s .c  o  m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast("http-codec", new HttpServerCodec());
                        pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
                        ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                        pipeline.addLast("handler", new WebSocketServerHandler());
                    }
                });

        Channel ch = b.bind(port).sync().channel();
        System.out.println("Web socket server started at port " + port + '.');
        System.out.println("Open your browser and navigate to http://localhost:" + port + '/');

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:chat.viska.xmpp.Connection.java

License:Apache License

private static Single<List<DnsRecord>> lookupDnsUsingNetty(final String query, final DnsRecordType type,
        @Nullable final Iterable<String> dns) {
    final NioEventLoopGroup threadPool = new NioEventLoopGroup();
    final DnsNameResolverBuilder builder = new DnsNameResolverBuilder(threadPool.next());
    builder.channelFactory(new ReflectiveChannelFactory<>(NioDatagramChannel.class));
    builder.decodeIdn(true);//  w w w.j  ava 2  s . c om
    if (dns != null) {
        builder.searchDomains(dns);
    }
    return Single.fromFuture(builder.build().query(new DefaultDnsQuestion(query, type)))
            .map(AddressedEnvelope::content).map(message -> {
                final int recordsSize = message.count(DnsSection.ANSWER);
                final List<DnsRecord> records = new ArrayList<>(recordsSize);
                for (int it = 0; it < recordsSize; ++it) {
                    records.add(message.recordAt(DnsSection.ANSWER, it));
                }
                return records;
            }).doFinally(threadPool::shutdownGracefully);
}

From source file:ChatClient.ChatClient.java

public void run() {
    EventLoopGroup group = new NioEventLoopGroup();

    try {/* www  . ja v  a2s  .  c om*/
        Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class)
                .handler(new ChatClientInitializer());
        Channel channel = bootstrap.connect(host, PORT).sync().channel();
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        while (true) {
            try {
                String line = in.readLine();
                channel.writeAndFlush(new StringMessage(0, 0, "Client", line));
                System.out.println("ECHO: " + line);
            } catch (IOException ex) {
                System.err.println("Writing error");
            }
        }
    } catch (InterruptedException ex) {
        System.err.println("Interrupt Error");
    } finally {
        group.shutdownGracefully();
    }
}

From source file:ChatServer.ChatServer.java

public void run() {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {//from w  w  w  . ja va 2s.c o m
        ServerBootstrap bootstrap = new ServerBootstrap().group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class).childHandler(new ChatServerInitializer());

        bootstrap.bind(port).channel().closeFuture().sync();
    } catch (InterruptedException ex) {
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:cl.uandes.so.server.LoginServer.java

public void run() throws Exception {
    final EventLoopGroup group = new NioEventLoopGroup(); // (1)

    try {//from w ww.  j  a va2 s.  c o m
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                System.out.println("Login Server will stop in 60 seconds...");
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(LoginServer.class.getName()).log(Level.SEVERE, null, ex);
                }
                group.shutdownGracefully();

            }
        });
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                int counter = 1;
                while (counter < 10) {
                    System.out.println("Time : " + counter);
                    try {
                        Thread.sleep(1000);
                        counter++;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t1.start();
        t2.start();
        Bootstrap b = new Bootstrap(); // (2)
        b.group(group).channel(NioDatagramChannel.class) // (3)
                .option(ChannelOption.SO_BROADCAST, true).handler(new LoginServerHandler(multicastgroup));

        // Bind and start to accept incoming connections.
        b.bind(port).sync().channel().closeFuture().await(); // (7)

    } finally {
        group.shutdownGracefully();
    }
}

From source file:client.DiscardClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from  w w w.j a v  a 2  s . co  m
        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();
    }
}

From source file:cloudeventbus.cli.Server.java

License:Open Source License

public static void main(String[] args) throws Exception {
    final JCommander commander = new JCommander();

    final Options options = new Options();
    commander.addObject(options);/*  ww  w  . jav a 2 s  .  co m*/

    commander.setProgramName("eventbus-server");

    try {
        commander.parse(args);

        DefaultOptions.setLogLevel(options);

        TrustStore trustStore = CertificateUtils.loadTrustStore(options.trustStore);
        if (trustStore != null && trustStore.size() > 0) {
            System.out.println("Using trust store at: " + options.trustStore);
        } else {
            trustStore = null;
        }

        final int port = options.port;

        final CertificateChain certificateChain;
        final PrivateKey privateKey;
        if (options.certificate == null) {
            certificateChain = null;
            privateKey = null;
        } else {
            certificateChain = CertificateUtils.loadCertificateChain(options.certificate);
            System.out.println("Using certificate at: " + options.certificate);
            if (options.privateKey == null) {
                System.err.print("You must specify a private key when using a certificate.");
                System.exit(1);
                return;
            } else {
                privateKey = CertificateUtils.loadPrivateKey(options.privateKey);
                System.out.println("Using private key at: " + options.privateKey);
            }
        }

        final NioEventLoopGroup parentGroup = new NioEventLoopGroup();
        final GlobalHub globalHub = new GlobalHub();
        final ServerConfig serverConfig = new ServerConfig(port, "cloudeventbus-simple-server", trustStore,
                certificateChain, privateKey);
        final ClusterManager clusterManager = new ClusterManager(serverConfig, globalHub, parentGroup);
        if (options.peers != null) {
            for (String peer : options.peers) {
                final String[] parts = peer.split(":");
                if (parts.length != 2) {
                    throw new IllegalArgumentException(
                            "Invalid peer address " + peer + " should be HOST:PORT (e.g. 127.0.0.1:4223)");
                }
                clusterManager.registerPeer(new InetSocketAddress(parts[0], Integer.valueOf(parts[1])));
            }
        }
        new ServerBootstrap().group(parentGroup, new NioEventLoopGroup()).channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(port))
                .childHandler(new ServerChannelInitializer(serverConfig, clusterManager, globalHub)).bind()
                .awaitUninterruptibly();
        System.out.println("Server listening on port " + port);
    } catch (ParameterException e) {
        System.err.println(e.getMessage());
        commander.usage();
        System.exit(1);
    }
}