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.chschmid.huemorse.server.HueMorse.java

License:Open Source License

/**
 * Start server huemorse server//from w ww  .  j  a  v  a2s  . c  o m
 */
private static void startServers() throws Exception {
    if (DEBUG)
        System.out.println("Starting servers");

    EventLoopGroup bossGroupHueMorse = new NioEventLoopGroup();
    EventLoopGroup workerGroupHueMorse = new NioEventLoopGroup();

    try {
        ServerBootstrap huemorse = new ServerBootstrap();

        huemorse.group(bossGroupHueMorse, workerGroupHueMorse).channel(NioServerSocketChannel.class)
                .childHandler(new MorseServerInitializer(hue));

        huemorse.bind(SERVER_PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroupHueMorse.shutdownGracefully();
        workerGroupHueMorse.shutdownGracefully();
    }
}

From source file:com.chschmid.pilight.server.PILight.java

License:Open Source License

/**
 * Starts who servers for pimorse and the more direct piglight interface
 * @param  light the PiLightInterface to operate on.
 *//*from w ww  . ja  va 2  s . com*/
private static void startServers(PiLightInterface light) throws Exception {
    if (DEBUG)
        System.out.println("Starting servers");
    light.start();

    EventLoopGroup bossGroupPiLight = new NioEventLoopGroup();
    EventLoopGroup workerGroupPiLight = new NioEventLoopGroup();
    EventLoopGroup bossGroupPiMorse = new NioEventLoopGroup();
    EventLoopGroup workerGroupPiMorse = new NioEventLoopGroup();

    try {
        ServerBootstrap pilight = new ServerBootstrap();
        ServerBootstrap pimorse = new ServerBootstrap();

        pilight.group(bossGroupPiLight, workerGroupPiLight).channel(NioServerSocketChannel.class)
                .childHandler(new LightServerInitializer(light));

        pimorse.group(bossGroupPiMorse, workerGroupPiMorse).channel(NioServerSocketChannel.class)
                .childHandler(new MorseServerInitializer(light));

        pilight.bind(LIGHT_SERVER_PORT).sync();
        pimorse.bind(MORSE_SERVER_PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroupPiLight.shutdownGracefully();
        workerGroupPiLight.shutdownGracefully();
        bossGroupPiMorse.shutdownGracefully();
        workerGroupPiMorse.shutdownGracefully();
    }

    light.stop();
}

From source file:com.cloudhopper.smpp.demo.RebindMain.java

License:Apache License

static public void main(String[] args) throws Exception {

    // a bootstrap can be shared (which will reused threads)
    // THIS VERSION USES "DAEMON" threads by default
    // SmppSessionBootstrap bootstrap = new SmppSessionBootstrap();
    // THIS VERSION DOESN'T - WILL HANG JVM UNTIL CLOSED
    final DefaultSmppClient bootstrap = new DefaultSmppClient(new NioEventLoopGroup());

    final DefaultSmppSessionHandler sessionHandler = new ClientSmppSessionHandler();

    final SmppSessionConfiguration config0 = new SmppSessionConfiguration();
    config0.setWindowSize(1);//from  w w  w  . ja v  a 2s .  co  m
    config0.setName("Tester.Session.0");
    config0.setType(SmppBindType.TRANSCEIVER);
    config0.setHost("localhost");
    config0.setPort(2776);
    config0.setConnectTimeout(10000);
    config0.setSystemId("smppclient1");
    config0.setPassword("password");

    Runnable bindRunnable = new Runnable() {

        public void run() {
            SmppSession session0 = null;
            try {
                while (true) {
                    // attempt to bind and create a session
                    session0 = bootstrap.bind(config0, sessionHandler);

                    Thread.sleep(10);

                    //
                    session0.enquireLink(new EnquireLink(), 10000);

                    Thread.sleep(10);

                    session0.close();

                    logger.info("Final pending Requests in Window: {}", session0.getRequestWindow().getSize());
                    logger.info("With windowSize=" + session0.getRequestWindow().getMaxSize());
                }
            } catch (Throwable t) {
                logger.error("{}", t);
            } finally {
                SmppSessionUtil.close(session0);
            }
        }

    };

    ExecutorService bindExecutor = Executors.newSingleThreadExecutor();
    bindExecutor.submit(bindRunnable);

    //Thread bindThread = new Thread(bindRunnable);
    //bindThread.start();

    System.out.println("Press any key to shutdown the threads");
    System.in.read();

    logger.info("Shutting down the bind executor, waiting up to 10 seconds");
    bindExecutor.shutdownNow();
    bindExecutor.awaitTermination(10000, TimeUnit.MILLISECONDS);

    System.out.println("Press any key to shutdown the bootstrap");
    System.in.read();

    // this is required to not causing server to hang from non-daemon threads
    // this also makes sure all open Channels are closed to I *think*
    logger.info("trying to shutdown bootstrap...");
    bootstrap.destroy();

    System.out.println("Press any key to exit");
    System.in.read();

    logger.info("Done. Exiting");
}

From source file:com.cloudhopper.smpp.demo.ServerMain.java

License:Apache License

static public void main(String[] args) throws Exception {
    ///*from   ww  w  . j a v  a  2 s.c o  m*/
    // setup 3 things required for a server
    //

    // create and assign the NioEventLoopGroup instances to handle event processing,
    // such as accepting new connections, receiving data, writing data, and so on.
    NioEventLoopGroup group = new NioEventLoopGroup();

    // to enable automatic expiration of requests, a second scheduled executor
    // is required which is what a monitor task will be executed with - this
    // is probably a thread pool that can be shared with between all client bootstraps
    ScheduledThreadPoolExecutor monitorExecutor = (ScheduledThreadPoolExecutor) Executors
            .newScheduledThreadPool(1, new ThreadFactory() {
                private AtomicInteger sequence = new AtomicInteger(0);

                @Override
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(r);
                    t.setName("SmppServerSessionWindowMonitorPool-" + sequence.getAndIncrement());
                    return t;
                }
            });

    // create a server configuration
    SmppServerConfiguration configuration = new SmppServerConfiguration();
    configuration.setPort(2776);
    configuration.setMaxConnectionSize(10);
    configuration.setNonBlockingSocketsEnabled(true);
    configuration.setDefaultRequestExpiryTimeout(30000);
    configuration.setDefaultWindowMonitorInterval(15000);
    configuration.setDefaultWindowSize(5);
    configuration.setDefaultWindowWaitTimeout(configuration.getDefaultRequestExpiryTimeout());
    configuration.setDefaultSessionCountersEnabled(true);
    configuration.setJmxEnabled(true);

    // create a server, start it up
    DefaultSmppServer smppServer = new DefaultSmppServer(configuration, new DefaultSmppServerHandler(),
            monitorExecutor, group, group);

    logger.info("Starting SMPP server...");
    smppServer.start();
    logger.info("SMPP server started");

    System.out.println("Press any key to stop server");
    System.in.read();

    logger.info("Stopping SMPP server...");
    smppServer.stop();
    logger.info("SMPP server stopped");

    logger.info("Server counters: {}", smppServer.getCounters());
}

From source file:com.cloudhopper.smpp.demo.SslServerMain.java

License:Apache License

static public void main(String[] args) throws Exception {
    ///*from  www. ja  va  2s.  co  m*/
    // setup 3 things required for a server
    //

    // create and assign the NioEventLoopGroup instances to handle event processing,
    // such as accepting new connections, receiving data, writing data, and so on.
    NioEventLoopGroup group = new NioEventLoopGroup();

    // to enable automatic expiration of requests, a second scheduled executor
    // is required which is what a monitor task will be executed with - this
    // is probably a thread pool that can be shared with between all client bootstraps
    ScheduledThreadPoolExecutor monitorExecutor = (ScheduledThreadPoolExecutor) Executors
            .newScheduledThreadPool(1, new ThreadFactory() {
                private AtomicInteger sequence = new AtomicInteger(0);

                @Override
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(r);
                    t.setName("SmppServerSessionWindowMonitorPool-" + sequence.getAndIncrement());
                    return t;
                }
            });

    // create a server configuration
    SmppServerConfiguration configuration = new SmppServerConfiguration();
    configuration.setPort(2777);
    configuration.setMaxConnectionSize(10);
    configuration.setNonBlockingSocketsEnabled(true);
    configuration.setDefaultRequestExpiryTimeout(30000);
    configuration.setDefaultWindowMonitorInterval(15000);
    configuration.setDefaultWindowSize(5);
    configuration.setDefaultWindowWaitTimeout(configuration.getDefaultRequestExpiryTimeout());
    configuration.setDefaultSessionCountersEnabled(true);
    configuration.setJmxEnabled(true);

    //ssl
    SslConfiguration sslConfig = new SslConfiguration();
    sslConfig.setKeyStorePath("src/test/resources/keystore");
    sslConfig.setKeyStorePassword("changeit");
    sslConfig.setKeyManagerPassword("changeit");
    sslConfig.setTrustStorePath("src/test/resources/keystore");
    sslConfig.setTrustStorePassword("changeit");
    configuration.setUseSsl(true);
    configuration.setSslConfiguration(sslConfig);

    // create a server, start it up
    DefaultSmppServer smppServer = new DefaultSmppServer(configuration, new DefaultSmppServerHandler(),
            monitorExecutor, group, group);

    logger.info("Starting SMPP server...");
    smppServer.start();
    logger.info("SMPP server started");

    System.out.println("Press any key to stop server");
    System.in.read();

    logger.info("Stopping SMPP server...");
    smppServer.stop();
    logger.info("SMPP server stopped");

    logger.info("Server counters: {}", smppServer.getCounters());
}

From source file:com.cloudhopper.smpp.impl.DefaultSmppClient.java

License:Apache License

/**
 * Creates a new default SmppClient. Window monitoring and automatic
 * expiration of requests will be disabled with no monitorExecutors.
 * The maximum number of IO worker threads across any client sessions
 * created with this SmppClient will be Runtime.getRuntime().availableProcessors().
 * An Executors.newCachedDaemonThreadPool will be used for IO worker threads.
 */// w w w .j  a v a 2  s  .  c  o m
public DefaultSmppClient() {
    this(new NioEventLoopGroup());
}

From source file:com.cloudhopper.smpp.impl.DefaultSmppServer.java

License:Apache License

/**
 * Creates a new default SmppServer. Window monitoring and automatic
 * expiration of requests will be disabled with no monitorExecutors.
 * A "cachedDaemonThreadPool" will be used for IO worker threads.
 * @param configuration The server configuration to create this server with
 * @param serverHandler The handler implementation for handling bind requests
 *      and creating/destroying sessions.
 *//*w w w . j  av a2 s.com*/
public DefaultSmppServer(SmppServerConfiguration configuration, SmppServerHandler serverHandler) {
    this(configuration, serverHandler, null,
            configuration.isNonBlockingSocketsEnabled() ? new NioEventLoopGroup() : new OioEventLoopGroup(),
            configuration.isNonBlockingSocketsEnabled() ? new NioEventLoopGroup() : new OioEventLoopGroup());
}

From source file:com.cloudhopper.smpp.simulator.SmppSimulatorServer.java

License:Apache License

public SmppSimulatorServer() {
    // used for tracking any child channels (sessions)
    this.sessionChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    // we'll put the "boss" worker for a server in its own pool
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();

    // tie the server bootstrap to this server socket channel factory
    this.serverBootstrap = new ServerBootstrap();
    this.serverBootstrap.channel(NioServerSocketChannel.class);
    this.serverBootstrap.group(bossGroup, workerGroup);

    // the handler to use when new child connections are accepted
    this.serverHandler = new SmppSimulatorServerHandler(this.sessionChannels);
    // set up the event pipeline factory for new connections
    this.serverBootstrap.childHandler(serverHandler);
}

From source file:com.cmz.http.snoop.HttpSnoopClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    URI uri = new URI(URL);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;//from w  w w. j  a v a 2s. c o  m
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        System.err.println("Only HTTP(S) is supported.");
        return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new HttpSnoopClientInitializer(sslCtx));

        // Make the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();

        // Prepare the HTTP request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                uri.getRawPath());
        request.headers().set(HttpHeaderNames.HOST, host);
        request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);

        // Set some example cookies.
        request.headers().set(HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT
                .encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar")));

        // Send the HTTP request.
        ch.writeAndFlush(request);

        // Wait for the server to close the connection.
        ch.closeFuture().sync();
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
    }
}

From source file:com.cmz.http.websocketx.client.WebSocketClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    URI uri = new URI(URL);
    String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
    final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if ("ws".equalsIgnoreCase(scheme)) {
            port = 80;/*from  ww  w  .  j  av  a  2s  . c  o m*/
        } else if ("wss".equalsIgnoreCase(scheme)) {
            port = 443;
        } else {
            port = -1;
        }
    } else {
        port = uri.getPort();
    }

    if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
        System.err.println("Only WS(S) is supported.");
        return;
    }

    final boolean ssl = "wss".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        // 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, true, new DefaultHttpHeaders()));

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
                }
                p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192),
                        WebSocketClientCompressionHandler.INSTANCE, handler);
            }
        });

        Channel ch = b.connect(uri.getHost(), port).sync().channel();
        handler.handshakeFuture().sync();

        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String msg = console.readLine();
            if (msg == null) {
                break;
            } else if ("bye".equals(msg.toLowerCase())) {
                ch.writeAndFlush(new CloseWebSocketFrame());
                ch.closeFuture().sync();
                break;
            } else if ("ping".equals(msg.toLowerCase())) {
                WebSocketFrame frame = new PingWebSocketFrame(
                        Unpooled.wrappedBuffer(new byte[] { 8, 1, 8, 1 }));
                ch.writeAndFlush(frame);
            } else {
                WebSocketFrame frame = new TextWebSocketFrame(msg);
                ch.writeAndFlush(frame);
            }
        }
    } finally {
        group.shutdownGracefully();
    }
}