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:com.github.mrstampy.gameboot.otp.netty.OtpNettyTestConfiguration.java

License:Open Source License

/**
 * Server clear bootstrap.//from  www. ja  va 2s . c om
 *
 * @return the server bootstrap
 * @throws Exception
 *           the exception
 */
@Bean(name = SERVER_CLEAR_BOOTSTRAP)
public ServerBootstrap serverClearBootstrap() throws Exception {
    //@formatter:off
    return new ServerBootstrap().channel(NioServerSocketChannel.class)
            .group(new NioEventLoopGroup(), new NioEventLoopGroup()).childHandler(clearServerInitializer());
    //@formatter:on
}

From source file:com.github.mrstampy.kitchensync.netty.Bootstrapper.java

License:Open Source License

/**
 * Gets the event loop group based upon the class name. If the class is
 * neither an <a href=//from   w  ww  .j  ava 2 s  .c  o m
 * "http://netty.io/4.0/api/io/netty/channel/socket/nio/NioDatagramChannel.html"
 * >NioDatagramChannel</a> nor <a href=
 * "http://netty.io/4.0/api/io/netty/channel/socket/oio/OioDatagramChannel.html"
 * >OioDatagramChannel</a> (or on Linux, <a href=
 * "http://netty.io/4.0/api/io/netty/channel/epoll/EpollDatagramChannel.html"
 * >EpollDatagramChannel</a>) then an exception is thrown.
 *
 * @param <CHANNEL>
 *          the generic type
 * @param clazz
 *          the clazz
 * @return the event loop group
 */
protected <CHANNEL extends DatagramChannel> EventLoopGroup getEventLoopGroup(Class<? extends CHANNEL> clazz) {
    if (NioDatagramChannel.class.equals(clazz))
        return new NioEventLoopGroup();

    if (OioDatagramChannel.class.equals(clazz))
        return new OioEventLoopGroup();

    // Linux only
    if (EpollDatagramChannel.class.equals(clazz))
        return new EpollEventLoopGroup();

    throw new UnsupportedOperationException("No default event loop group defined for " + clazz.getName());
}

From source file:com.github.nettybook.ch4.EchoClient.java

License:Apache License

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

    try {// www. j a  v a2s  .c  om
        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();
    }
}

From source file:com.github.spapageo.jannel.client.ClientSessionTest.java

License:Open Source License

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    clientSessionConfiguration = new ClientSessionConfiguration();
    clientSessionConfiguration.setWindowSize(2);
    scheduledExecutorService = new ScheduledThreadPoolExecutor(2);

    clientSession = new ClientSession(clientSessionConfiguration, channel, timer, sessionHandler);
    eventExecutors = new NioEventLoopGroup();
}

From source file:com.github.thinker0.mesos.MesosHealthCheckerServer.java

License:Apache License

/**
 * Starts the web server./*from   w w w.j  a v  a2s . c  o m*/
 *
 * @throws Exception
 */
public EventLoopGroup start() throws Exception {
    if (Epoll.isAvailable()) {
        eventLoopGroup = new EpollEventLoopGroup();
        start(new EpollEventLoopGroup(), EpollServerSocketChannel.class);
    } else {
        eventLoopGroup = new NioEventLoopGroup();
        start(new NioEventLoopGroup(), NioServerSocketChannel.class);
    }
    return eventLoopGroup;
}

From source file:com.github.vitrifiedcode.javautilities.netty.DiscardServer.java

License:Open Source License

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from ww w  .  j  ava 2  s .com
        ServerBootstrap b = new ServerBootstrap(); // (2)
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) // (3)
                .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new DiscardServerHandler());
                    }
                }).option(ChannelOption.SO_BACKLOG, 128) // (5)
                .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

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

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

From source file:com.github.wangshuwei5.server.NettyServer.java

License:Apache License

public void bind() throws Exception {
    // ??NIO/*from www  .j  a v  a2 s.c om*/
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new NettyServerInitializer(SSLMODE.CSA.toString()));

        // ???
        ChannelFuture f = b.bind(NettyConstant.REMOTEIP, NettyConstant.PORT).sync();

        // ???
        f.channel().closeFuture().sync();

        System.out.println("Netty server start ok : " + (NettyConstant.REMOTEIP + " : " + NettyConstant.PORT));
    } finally {
        // ?
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.glabs.homegenie.client.eventsource.EventSourceTask.java

License:Open Source License

protected Void doInBackground(String... urls) {
    try {//from ww  w  .  j av  a2s  . c  om
        eventSource = new EventSource(urls[0], Control.getAuthUser(), Control.getAuthPassword(),
                new NioEventLoopGroup(), this);
    } catch (Exception e) {
        this.exception = e;
    }
    return null;
}

From source file:com.google.cloud.pubsub.proxy.moquette.NettyAcceptor.java

License:Open Source License

/**
 * Initialize the the various transport protocols for this server,
 * and setup their handlers/callbacks.// w  ww  .j a  v  a2s.  co m
 */
@Override
public void initialize(IMessaging messaging, Properties props) throws IOException {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();

    initializePlainTcpTransport(messaging, props);
    initializeWebSocketTransport(messaging, props);
    String sslTcpPortProp = props.getProperty(Constants.SSL_PORT_PROPERTY_NAME);
    String wssPortProp = props.getProperty(Constants.WSS_PORT_PROPERTY_NAME);
    if (sslTcpPortProp != null || wssPortProp != null) {
        SslHandler sslHandler = initSslHandler(props);
        if (sslHandler == null) {
            LOG.error("Can't initialize SSLHandler layer! Exiting, check your configuration of jks");
            return;
        }
        initializeSslTcpTransport(messaging, props, sslHandler);
        initializeWssTransport(messaging, props, sslHandler);
    }
    // initialize ProxyContext and Pubsub impl
    context.open();
    pubsub.initialize(context);
}

From source file:com.googlecode.protobuf.pro.duplex.example.DuplexPingPongClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    if (args.length != 8) {
        System.err.println(/* w  ww  .  j  av a  2s. co m*/
                "usage: <serverHostname> <serverPort> <clientHostname> <clientPort> <ssl=Y/N> <nodelay=Y/N> <compress=Y/N> <payloadSizeBytes>");
        System.exit(-1);
    }
    String serverHostname = args[0];
    int serverPort = Integer.parseInt(args[1]);
    String clientHostname = args[2];
    int clientPort = Integer.parseInt(args[3]);
    boolean secure = "Y".equals(args[4]);
    boolean nodelay = "Y".equals(args[5]);
    boolean compress = "Y".equals(args[6]);
    int payloadSize = Integer.parseInt(args[7]);

    log.info("DuplexPingPongClient port=" + clientPort + " ssl=" + (secure ? "Y" : "N") + " nodelay="
            + (nodelay ? "Y" : "N") + " compress=" + (compress ? "Y" : "N") + " payloadSizeBytes="
            + payloadSize);

    PeerInfo client = new PeerInfo(clientHostname, clientPort);
    PeerInfo server = new PeerInfo(serverHostname, serverPort);

    RpcServerCallExecutor executor = new ThreadPoolCallExecutor(3, 100);

    DuplexTcpClientPipelineFactory clientFactory = new DuplexTcpClientPipelineFactory();
    clientFactory.setClientInfo(client); // forces a local port nr.

    clientFactory.setConnectResponseTimeoutMillis(10000);
    clientFactory.setRpcServerCallExecutor(executor);
    clientFactory.setCompression(compress);
    if (secure) {
        RpcSSLContext sslCtx = new RpcSSLContext();
        sslCtx.setKeystorePassword("changeme");
        sslCtx.setKeystorePath("./lib/client.keystore");
        sslCtx.setTruststorePassword("changeme");
        sslCtx.setTruststorePath("./lib/truststore");
        sslCtx.init();

        clientFactory.setSslContext(sslCtx);
    }

    NullLogger logger = new NullLogger();
    clientFactory.setRpcLogger(logger);

    RpcTimeoutExecutor timeoutExecutor = new TimeoutExecutor(1, 5);
    RpcTimeoutChecker checker = new TimeoutChecker();
    checker.setTimeoutExecutor(timeoutExecutor);
    checker.startChecking(clientFactory.getRpcClientRegistry());

    CleanShutdownHandler shutdownHandler = new CleanShutdownHandler();
    shutdownHandler.addResource(executor);
    shutdownHandler.addResource(checker);
    shutdownHandler.addResource(timeoutExecutor);

    // setup a RPC event listener - it just logs what happens
    RpcConnectionEventNotifier rpcEventNotifier = new RpcConnectionEventNotifier();
    RpcConnectionEventListener listener = new RpcConnectionEventListener() {

        @Override
        public void connectionReestablished(RpcClientChannel clientChannel) {
            log.info("connectionReestablished " + clientChannel);
        }

        @Override
        public void connectionOpened(RpcClientChannel clientChannel) {
            log.info("connectionOpened " + clientChannel);
        }

        @Override
        public void connectionLost(RpcClientChannel clientChannel) {
            log.info("connectionLost " + clientChannel);
        }

        @Override
        public void connectionChanged(RpcClientChannel clientChannel) {
            log.info("connectionChanged " + clientChannel);
        }
    };
    rpcEventNotifier.setEventListener(listener);
    clientFactory.registerConnectionEventListener(rpcEventNotifier);

    // Configure the client to provide a Pong Service in both blocking an non blocking varieties
    BlockingService bPongService = BlockingPongService
            .newReflectiveBlockingService(new PingPongServiceFactory.BlockingPongServer());
    clientFactory.getRpcServiceRegistry().registerService(bPongService);

    Service nbPongService = NonBlockingPongService
            .newReflectiveService(new PingPongServiceFactory.NonBlockingPongServer());
    clientFactory.getRpcServiceRegistry().registerService(nbPongService);

    // we give the client a blocking and non blocking (pong capable) Ping Service
    BlockingService bPingService = BlockingPingService
            .newReflectiveBlockingService(new PingPongServiceFactory.BlockingPongingPingServer());
    clientFactory.getRpcServiceRegistry().registerService(bPingService);

    Service nbPingService = NonBlockingPingService
            .newReflectiveService(new PingPongServiceFactory.NonBlockingPongingPingServer());
    clientFactory.getRpcServiceRegistry().registerService(nbPingService);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(new NioEventLoopGroup());
    bootstrap.handler(clientFactory);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.TCP_NODELAY, nodelay);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
    bootstrap.option(ChannelOption.SO_SNDBUF, 1048576);
    bootstrap.option(ChannelOption.SO_RCVBUF, 1048576);

    shutdownHandler.addResource(bootstrap.group());

    try {
        clientFactory.peerWith(server, bootstrap);

        while (true) {

            new ShortTests().execute(clientFactory.getRpcClientRegistry());

            new AllClientTests().execute(clientFactory.getRpcClientRegistry());

            new ClientPerformanceTests().execute(clientFactory.getRpcClientRegistry());

            Thread.sleep(60000);
        }
    } catch (Throwable e) {
        log.error("Throwable.", e);
    } finally {
        System.exit(0);
    }
}