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.barchart.http.server.TestBenchmark.java

License:BSD License

public static void main(final String[] args) {

    final HttpServer server = new HttpServer();

    final HttpServerConfig config = new HttpServerConfig().requestHandler("", new TestRequestHandler())
            .address(new InetSocketAddress("localhost", 8080)).parentGroup(new NioEventLoopGroup())
            .childGroup(new NioEventLoopGroup()).maxConnections(-1);

    try {/*from   w w  w  . jav a2 s  .  c  o  m*/
        server.configure(config).listen().sync();
        server.shutdownFuture().sync();
    } catch (final InterruptedException e) {
    }

}

From source file:com.barchart.netty.client.base.ConnectableBase.java

License:BSD License

/**
 * Create a new Connectable client. This method is intended to be called by
 * subclass Builder implementations.//from   w ww.j  a  v a 2  s  . c om
 *
 * @param eventLoop_ The Netty EventLoopGroup to use for transport
 *            operations
 * @param address_ The remote peer address
 * @param transport_ The transport type
 */
protected ConnectableBase(final TransportProtocol transport_) {

    transport = transport_;

    group = new NioEventLoopGroup();

    channelInitializer = new ClientPipelineInitializer();

}

From source file:com.barchart.netty.server.http.handlers.TestStaticResourceHandler.java

License:BSD License

@Before
public void setUp() throws Exception {

    final ServerSocket s = new ServerSocket(0);
    port = s.getLocalPort();/*w w  w.j a  v a 2s.com*/
    s.close();

    server = Servers.createHttpServer().group(new NioEventLoopGroup())
            .requestHandler("/classpath", new StaticResourceHandler(this.getClass().getClassLoader(), "/files"))
            .requestHandler("/file", new StaticResourceHandler(
                    new File(System.getProperty("user.dir") + "/src/test/resources/files")));

    server.listen(port, "localhost");

    client = new DefaultHttpClient(new PoolingClientConnectionManager());

}

From source file:com.barchart.netty.server.http.TestBenchmark.java

License:BSD License

public static void main(final String[] args) {

    final HttpServer server = Servers.createHttpServer().requestHandler("", new TestRequestHandler())
            .requestHandler("/test", new TestWebSocketPage())
            .webSocketHandler("/ws", new TestWebsocketHandler("1"))
            .webSocketHandler("/ws2", new TestWebsocketHandler("2")).group(new NioEventLoopGroup())
            .maxConnections(-1);//from   w  w  w.  j  a  v a  2s. c o  m

    server.listen(8080);

    try {
        server.shutdownFuture().sync();
    } catch (final InterruptedException e) {
    }

}

From source file:com.base.research.socket.netty.Client.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {//from  w  w w  .  java2  s . c om
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                // ch.pipeline().addLast(new TimeDecode());
                ch.pipeline().addLast(new TestDecode2());
                // ch.pipeline().addLast(new TestEncode());
                ch.pipeline().addLast(new TestEncode2());
                ch.pipeline().addLast(new ClientHandler());
            }
        });

        // 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:com.base.research.socket.netty.Server.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from  w  w w. j ava  2  s  . c om
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        // ch.pipeline().addLast(new TimeDecode());
                        ch.pipeline().addLast(new TestDecode2());
                        // ch.pipeline().addLast(new TestEncode());
                        ch.pipeline().addLast(new TestEncode2());
                        ch.pipeline().addLast(new ServerHandler());
                    }
                });

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

        // 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.basho.riak.client.core.ConnectionPool.java

License:Apache License

/**
 * Starts this connection pool./*  w  w w  . j a v a 2  s  .  c  o  m*/
 * <p/>
 * If {@code minConnections} has been set, that number of active connections
 * will be started and placed into the available queue. Note that if they
 * can not be established due to the Riak node being down, a network issue,
 * etc this will not prevent the pool from changing to a started state.
 *
 * @return this
 */
public synchronized ConnectionPool start() {
    stateCheck(State.CREATED);
    if (bootstrap == null) {
        this.bootstrap = new Bootstrap().group(new NioEventLoopGroup()).channel(NioSocketChannel.class);
        ownsBootstrap = true;
    }

    bootstrap.handler(protocol.channelInitializer()).remoteAddress(new InetSocketAddress(remoteAddress, port));

    if (connectionTimeout > 0) {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeout);
    }

    if (executor == null) {
        executor = Executors.newSingleThreadScheduledExecutor();
        ownsExecutor = true;
    }

    if (minConnections > 0) {
        List<Channel> minChannels = new LinkedList<Channel>();
        for (int i = 0; i < minConnections; i++) {
            Channel channel;
            try {
                channel = doGetConnection();
                minChannels.add(channel);
            } catch (ConnectionFailedException ex) {
                // no-op, we don't care right now
            }
        }

        for (Channel c : minChannels) {
            available.offerFirst(new ChannelWithIdleTime(c));
        }
    }

    idleReaperFuture = executor.scheduleWithFixedDelay(new IdleReaper(), 1, 5, TimeUnit.SECONDS);
    healthMonitorFuture = executor.scheduleWithFixedDelay(new HealthMonitorTask(), 1000, 500,
            TimeUnit.MILLISECONDS);
    state = State.RUNNING;
    logger.info("ConnectionPool started; {}:{} {}", remoteAddress, port, protocol);
    notifyStateListeners();
    return this;
}

From source file:com.basho.riak.client.core.RiakCluster.java

License:Apache License

private RiakCluster(Builder builder) throws UnknownHostException {
    this.executionAttempts = builder.executionAttempts;

    if (null == builder.nodeManager) {
        nodeManager = new DefaultNodeManager();
    } else {//www  .  jav a2s.  c o  m
        this.nodeManager = builder.nodeManager;
    }

    if (builder.bootstrap != null) {
        this.bootstrap = builder.bootstrap.clone();
    } else {
        this.bootstrap = new Bootstrap().group(new NioEventLoopGroup()).channel(NioSocketChannel.class);
    }

    if (builder.executor != null) {
        executor = builder.executor;
    } else {
        // We still need an executor if none was provided. 
        executor = new ScheduledThreadPoolExecutor(2);
    }

    nodeList = new ArrayList<RiakNode>(builder.riakNodes.size());
    for (RiakNode node : builder.riakNodes) {
        node.setExecutor(executor);
        node.setBootstrap(bootstrap);
        node.addStateListener(nodeManager);
        nodeList.add(node);
    }

    // Pass a *copy* of the list to the NodeManager
    nodeManager.init(new ArrayList<RiakNode>(nodeList));
    state = State.CREATED;
}

From source file:com.basho.riak.client.core.RiakNode.java

License:Apache License

public synchronized RiakNode start() {
    stateCheck(State.CREATED);/*from  w  ww .  j ava 2s .co  m*/

    if (executor == null) {
        executor = Executors.newSingleThreadScheduledExecutor();
        ownsExecutor = true;
    }

    if (bootstrap == null) {
        bootstrap = new Bootstrap().group(new NioEventLoopGroup()).channel(NioSocketChannel.class);
        ownsBootstrap = true;
    }

    bootstrap.handler(new RiakChannelInitializer(this))
            .remoteAddress(new InetSocketAddress(remoteAddress, port));

    if (connectionTimeout > 0) {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeout);
    }

    if (minConnections > 0) {
        List<Channel> minChannels = new LinkedList<Channel>();
        for (int i = 0; i < minConnections; i++) {
            Channel channel;
            try {
                channel = doGetConnection();
                minChannels.add(channel);
            } catch (ConnectionFailedException ex) {
                // no-op, we don't care right now
            }
        }

        for (Channel c : minChannels) {
            available.offerFirst(new ChannelWithIdleTime(c));
            c.closeFuture().addListener(inAvailableCloseListener);
        }
    }

    idleReaperFuture = executor.scheduleWithFixedDelay(new IdleReaper(), 1, 5, TimeUnit.SECONDS);
    healthMonitorFuture = executor.scheduleWithFixedDelay(new HealthMonitorTask(), 1000, 1000,
            TimeUnit.MILLISECONDS);

    state = State.RUNNING;
    logger.info("RiakNode started; {}:{}", remoteAddress, port);
    notifyStateListeners();
    return this;
}

From source file:com.bdtools.doxecute.WorldClockClient.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*from  w  w  w .ja v  a  2  s. co m*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new WorldClockClientInitializer());

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

        // Get the handler instance to initiate the request.
        WorldClockClientHandler handler = ch.pipeline().get(WorldClockClientHandler.class);

        // Request and get the response.
        List<String> response = handler.getLocalTimes(cities);

        // Close the connection.
        ch.close();

        // Print the response at last but not least.
        Iterator<String> i1 = cities.iterator();
        Iterator<String> i2 = response.iterator();
        while (i1.hasNext()) {
            System.out.format("%28s: %s%n", i1.next(), i2.next());
        }
    } finally {
        group.shutdownGracefully();
    }
}