Example usage for io.netty.channel DefaultEventLoopGroup DefaultEventLoopGroup

List of usage examples for io.netty.channel DefaultEventLoopGroup DefaultEventLoopGroup

Introduction

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

Prototype

public DefaultEventLoopGroup() 

Source Link

Document

Create a new instance with the default number of threads.

Usage

From source file:com.flysoloing.learning.network.netty.localecho.LocalEcho.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Address to bind on / connect to.
    final LocalAddress addr = new LocalAddress(PORT);

    EventLoopGroup serverGroup = new DefaultEventLoopGroup();
    EventLoopGroup clientGroup = new NioEventLoopGroup(); // NIO event loops are also OK
    try {// w  ww  . j a  v  a 2s  . c  o  m
        // Note that we can use any event loop to ensure certain local channels
        // are handled by the same event loop thread which drives a certain socket channel
        // to reduce the communication latency between socket channels and local channels.
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(serverGroup).channel(LocalServerChannel.class)
                .handler(new ChannelInitializer<LocalServerChannel>() {
                    @Override
                    public void initChannel(LocalServerChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
                    }
                }).childHandler(new ChannelInitializer<LocalChannel>() {
                    @Override
                    public void initChannel(LocalChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoServerHandler());
                    }
                });

        Bootstrap cb = new Bootstrap();
        cb.group(clientGroup).channel(LocalChannel.class).handler(new ChannelInitializer<LocalChannel>() {
            @Override
            public void initChannel(LocalChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoClientHandler());
            }
        });

        // Start the server.
        sb.bind(addr).sync();

        // Start the client.
        Channel ch = cb.connect(addr).sync().channel();

        // Read commands from the stdin.
        System.out.println("Enter text (quit to end)");
        ChannelFuture lastWriteFuture = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (;;) {
            String line = in.readLine();
            if (line == null || "quit".equalsIgnoreCase(line)) {
                break;
            }

            // Sends the received line to the server.
            lastWriteFuture = ch.writeAndFlush(line);
        }

        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.awaitUninterruptibly();
        }
    } finally {
        serverGroup.shutdownGracefully();
        clientGroup.shutdownGracefully();
    }
}

From source file:com.hxr.javatone.concurrency.netty.official.localecho.LocalEcho.java

License:Apache License

public void run() throws Exception {
    // Address to bind on / connect to.
    final LocalAddress addr = new LocalAddress(port);

    EventLoopGroup serverGroup = new DefaultEventLoopGroup();
    EventLoopGroup clientGroup = new NioEventLoopGroup(); // NIO event loops are also OK
    try {/*from w w w.  j  a v  a 2 s . com*/
        // Note that we can use any event loop to ensure certain local channels
        // are handled by the same event loop thread which drives a certain socket channel
        // to reduce the communication latency between socket channels and local channels.
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(serverGroup).channel(LocalServerChannel.class)
                .handler(new ChannelInitializer<LocalServerChannel>() {
                    @Override
                    public void initChannel(LocalServerChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
                    }
                }).childHandler(new ChannelInitializer<LocalChannel>() {
                    @Override
                    public void initChannel(LocalChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoServerHandler());
                    }
                });

        Bootstrap cb = new Bootstrap();
        cb.group(clientGroup).channel(LocalChannel.class).handler(new ChannelInitializer<LocalChannel>() {
            @Override
            public void initChannel(LocalChannel ch) throws Exception {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO), new LocalEchoClientHandler());
            }
        });

        // Start the server.
        sb.bind(addr).sync();

        // Start the client.
        Channel ch = cb.connect(addr).sync().channel();

        // Read commands from the stdin.
        System.out.println("Enter text (quit to end)");
        ChannelFuture lastWriteFuture = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (;;) {
            String line = in.readLine();
            if (line == null || "quit".equalsIgnoreCase(line)) {
                break;
            }

            // Sends the received line to the server.
            lastWriteFuture = ch.writeAndFlush(line);
        }

        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.awaitUninterruptibly();
        }
    } finally {
        serverGroup.shutdownGracefully();
        clientGroup.shutdownGracefully();
    }
}

From source file:herddb.client.HDBClient.java

License:Apache License

private void init() {
    int corePoolSize = configuration.getInt(ClientConfiguration.PROPERTY_CLIENT_CALLBACKS,
            ClientConfiguration.PROPERTY_CLIENT_CALLBACKS_DEFAULT);
    this.thredpool = new ThreadPoolExecutor(corePoolSize, Integer.MAX_VALUE, 120L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(), (Runnable r) -> {
                Thread t = new FastThreadLocalThread(r, "hdb-client");
                t.setDaemon(true);/*from   w  w  w  .  jav  a2 s.  c o  m*/
                return t;
            });
    this.networkGroup = NetworkUtils.isEnableEpoolNative() ? new EpollEventLoopGroup()
            : new NioEventLoopGroup();
    this.localEventsGroup = new DefaultEventLoopGroup();
    String mode = configuration.getString(ClientConfiguration.PROPERTY_MODE,
            ClientConfiguration.PROPERTY_MODE_LOCAL);
    switch (mode) {
    case ClientConfiguration.PROPERTY_MODE_LOCAL:
    case ClientConfiguration.PROPERTY_MODE_STANDALONE:
        this.clientSideMetadataProvider = new StaticClientSideMetadataProvider(
                configuration.getString(ClientConfiguration.PROPERTY_SERVER_ADDRESS,
                        ClientConfiguration.PROPERTY_SERVER_ADDRESS_DEFAULT),
                configuration.getInt(ClientConfiguration.PROPERTY_SERVER_PORT,
                        ClientConfiguration.PROPERTY_SERVER_PORT_DEFAULT),
                configuration.getBoolean(ClientConfiguration.PROPERTY_SERVER_SSL,
                        ClientConfiguration.PROPERTY_SERVER_SSL_DEFAULT));
        break;
    case ClientConfiguration.PROPERTY_MODE_CLUSTER:
        this.clientSideMetadataProvider = new ZookeeperClientSideMetadataProvider(
                configuration.getString(ClientConfiguration.PROPERTY_ZOOKEEPER_ADDRESS,
                        ClientConfiguration.PROPERTY_ZOOKEEPER_ADDRESS_DEFAULT),
                configuration.getInt(ClientConfiguration.PROPERTY_ZOOKEEPER_SESSIONTIMEOUT,
                        ClientConfiguration.PROPERTY_ZOOKEEPER_SESSIONTIMEOUT_DEFAULT),
                configuration.getString(ClientConfiguration.PROPERTY_ZOOKEEPER_PATH,
                        ClientConfiguration.PROPERTY_ZOOKEEPER_PATH_DEFAULT));
        break;
    default:
        throw new IllegalStateException(mode);
    }
}

From source file:io.airlift.drift.transport.netty.client.TestConnectionPool.java

License:Apache License

@Test
public void testPooling() {
    try (ConnectionPool pool = new ConnectionPool(new TestingConnectionManager(), new DefaultEventLoopGroup(),
            10, new Duration(1, MINUTES))) {
        HostAndPort address1 = HostAndPort.fromParts("localhost", 1234);
        HostAndPort address2 = HostAndPort.fromParts("localhost", 4567);

        Channel channel1 = futureGet(pool.getConnection(PARAMETERS, address1));
        Channel channel2 = futureGet(pool.getConnection(PARAMETERS, address1));
        assertSame(channel1, channel2);//from  ww w  . j av a2s.c  o m

        Channel channel3 = futureGet(pool.getConnection(PARAMETERS, address2));
        assertNotSame(channel1, channel3);

        Channel channel4 = futureGet(pool.getConnection(PARAMETERS, address1));
        assertSame(channel1, channel4);
    }
}

From source file:io.airlift.drift.transport.netty.client.TestConnectionPool.java

License:Apache License

@Test
public void testConnectionClosed() {
    try (ConnectionPool pool = new ConnectionPool(new TestingConnectionManager(), new DefaultEventLoopGroup(),
            10, new Duration(1, MINUTES))) {
        HostAndPort address = HostAndPort.fromParts("localhost", 1234);

        Channel channel1 = futureGet(pool.getConnection(PARAMETERS, address));
        assertTrue(channel1.isOpen());/*from  www.  java2  s .c o  m*/
        channel1.close();
        assertFalse(channel1.isOpen());

        Channel channel2 = futureGet(pool.getConnection(PARAMETERS, address));
        assertTrue(channel2.isOpen());
        assertNotSame(channel1, channel2);
    }
}

From source file:io.grpc.benchmarks.TransportBenchmark.java

License:Apache License

@Setup
@SuppressWarnings("LiteralClassName") // Epoll is not available on windows
public void setUp() throws Exception {
    AbstractServerImplBuilder<?> serverBuilder;
    AbstractManagedChannelImplBuilder<?> channelBuilder;
    switch (transport) {
    case INPROCESS: {
        String name = "bench" + Math.random();
        serverBuilder = InProcessServerBuilder.forName(name);
        channelBuilder = InProcessChannelBuilder.forName(name);
        break;// ww w  .  ja  v  a 2  s.c om
    }
    case NETTY: {
        InetSocketAddress address = new InetSocketAddress("localhost", pickUnusedPort());
        serverBuilder = NettyServerBuilder.forAddress(address);
        channelBuilder = NettyChannelBuilder.forAddress(address).negotiationType(NegotiationType.PLAINTEXT);
        break;
    }
    case NETTY_LOCAL: {
        String name = "bench" + Math.random();
        LocalAddress address = new LocalAddress(name);
        EventLoopGroup group = new DefaultEventLoopGroup();
        serverBuilder = NettyServerBuilder.forAddress(address).bossEventLoopGroup(group)
                .workerEventLoopGroup(group).channelType(LocalServerChannel.class);
        channelBuilder = NettyChannelBuilder.forAddress(address).eventLoopGroup(group)
                .channelType(LocalChannel.class).negotiationType(NegotiationType.PLAINTEXT);
        groupToShutdown = group;
        break;
    }
    case NETTY_EPOLL: {
        InetSocketAddress address = new InetSocketAddress("localhost", pickUnusedPort());

        // Reflection used since they are only available on linux.
        Class<?> groupClass = Class.forName("io.netty.channel.epoll.EpollEventLoopGroup");
        EventLoopGroup group = (EventLoopGroup) groupClass.getConstructor().newInstance();

        @SuppressWarnings("unchecked")
        Class<? extends ServerChannel> serverChannelClass = (Class<? extends ServerChannel>) Class
                .forName("io.netty.channel.epoll.EpollServerSocketChannel");
        serverBuilder = NettyServerBuilder.forAddress(address).bossEventLoopGroup(group)
                .workerEventLoopGroup(group).channelType(serverChannelClass);
        @SuppressWarnings("unchecked")
        Class<? extends Channel> channelClass = (Class<? extends Channel>) Class
                .forName("io.netty.channel.epoll.EpollSocketChannel");
        channelBuilder = NettyChannelBuilder.forAddress(address).eventLoopGroup(group).channelType(channelClass)
                .negotiationType(NegotiationType.PLAINTEXT);
        groupToShutdown = group;
        break;
    }
    case OKHTTP: {
        int port = pickUnusedPort();
        InetSocketAddress address = new InetSocketAddress("localhost", port);
        serverBuilder = NettyServerBuilder.forAddress(address);
        channelBuilder = OkHttpChannelBuilder.forAddress("localhost", port).usePlaintext();
        break;
    }
    default:
        throw new Exception("Unknown transport: " + transport);
    }

    if (direct) {
        serverBuilder.directExecutor();
        // Because blocking stubs avoid the executor, this doesn't do much.
        channelBuilder.directExecutor();
    }

    server = serverBuilder.addService(new AsyncServer.BenchmarkServiceImpl()).build();
    server.start();
    channel = channelBuilder.build();
    stub = BenchmarkServiceGrpc.newBlockingStub(channel);
    asyncStub = BenchmarkServiceGrpc.newStub(channel);
    // Wait for channel to start
    stub.unaryCall(SimpleRequest.getDefaultInstance());
}

From source file:org.apache.bookkeeper.proto.PerChannelBookieClient.java

License:Apache License

public PerChannelBookieClient(ClientConfiguration conf, OrderedExecutor executor, EventLoopGroup eventLoopGroup,
        ByteBufAllocator allocator, BookieSocketAddress addr, StatsLogger parentStatsLogger,
        ClientAuthProvider.Factory authProviderFactory, ExtensionRegistry extRegistry,
        PerChannelBookieClientPool pcbcPool, SecurityHandlerFactory shFactory) throws SecurityException {
    this.maxFrameSize = conf.getNettyMaxFrameSizeBytes();
    this.conf = conf;
    this.addr = addr;
    this.executor = executor;
    if (LocalBookiesRegistry.isLocalBookie(addr)) {
        this.eventLoopGroup = new DefaultEventLoopGroup();
    } else {/*w ww  . j a v  a  2 s . c o m*/
        this.eventLoopGroup = eventLoopGroup;
    }
    this.allocator = allocator;
    this.state = ConnectionState.DISCONNECTED;
    this.addEntryTimeoutNanos = TimeUnit.SECONDS.toNanos(conf.getAddEntryTimeout());
    this.readEntryTimeoutNanos = TimeUnit.SECONDS.toNanos(conf.getReadEntryTimeout());
    this.getBookieInfoTimeout = conf.getBookieInfoTimeout();
    this.startTLSTimeout = conf.getStartTLSTimeout();
    this.useV2WireProtocol = conf.getUseV2WireProtocol();
    this.preserveMdcForTaskExecution = conf.getPreserveMdcForTaskExecution();

    this.authProviderFactory = authProviderFactory;
    this.extRegistry = extRegistry;
    this.shFactory = shFactory;
    if (shFactory != null) {
        shFactory.init(NodeType.Client, conf, allocator);
    }

    StringBuilder nameBuilder = new StringBuilder();
    nameBuilder.append(addr.getHostName().replace('.', '_').replace('-', '_')).append("_")
            .append(addr.getPort());

    this.statsLogger = parentStatsLogger.scope(BookKeeperClientStats.CHANNEL_SCOPE)
            .scope(nameBuilder.toString());

    readEntryOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_READ_OP);
    addEntryOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_ADD_OP);
    writeLacOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_WRITE_LAC_OP);
    forceLedgerOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_FORCE_OP);
    readLacOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_READ_LAC_OP);
    getBookieInfoOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.GET_BOOKIE_INFO_OP);
    getListOfEntriesOfLedgerCompletionOpLogger = statsLogger
            .getOpStatsLogger(BookKeeperClientStats.GET_LIST_OF_ENTRIES_OF_LEDGER_OP);
    readTimeoutOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_TIMEOUT_READ);
    addTimeoutOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_TIMEOUT_ADD);
    writeLacTimeoutOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_TIMEOUT_WRITE_LAC);
    forceLedgerTimeoutOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_TIMEOUT_FORCE);
    readLacTimeoutOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_TIMEOUT_READ_LAC);
    getBookieInfoTimeoutOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.TIMEOUT_GET_BOOKIE_INFO);
    startTLSOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_START_TLS_OP);
    startTLSTimeoutOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_TIMEOUT_START_TLS_OP);
    getListOfEntriesOfLedgerCompletionTimeoutOpLogger = statsLogger
            .getOpStatsLogger(BookKeeperClientStats.TIMEOUT_GET_LIST_OF_ENTRIES_OF_LEDGER);
    exceptionCounter = statsLogger.getCounter(BookKeeperClientStats.NETTY_EXCEPTION_CNT);
    connectTimer = statsLogger.getOpStatsLogger(BookKeeperClientStats.CLIENT_CONNECT_TIMER);
    addEntryOutstanding = statsLogger.getCounter(BookKeeperClientStats.ADD_OP_OUTSTANDING);
    readEntryOutstanding = statsLogger.getCounter(BookKeeperClientStats.READ_OP_OUTSTANDING);
    nettyOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.NETTY_OPS);
    activeNonTlsChannelCounter = statsLogger.getCounter(BookKeeperClientStats.ACTIVE_NON_TLS_CHANNEL_COUNTER);
    activeTlsChannelCounter = statsLogger.getCounter(BookKeeperClientStats.ACTIVE_TLS_CHANNEL_COUNTER);
    failedConnectionCounter = statsLogger.getCounter(BookKeeperClientStats.FAILED_CONNECTION_COUNTER);
    failedTlsHandshakeCounter = statsLogger.getCounter(BookKeeperClientStats.FAILED_TLS_HANDSHAKE_COUNTER);

    this.pcbcPool = pcbcPool;

    this.connectionPeer = new ClientConnectionPeer() {

        @Override
        public SocketAddress getRemoteAddr() {
            Channel c = channel;
            if (c != null) {
                return c.remoteAddress();
            } else {
                return null;
            }
        }

        @Override
        public Collection<Object> getProtocolPrincipals() {
            Channel c = channel;
            if (c == null) {
                return Collections.emptyList();
            }
            SslHandler ssl = c.pipeline().get(SslHandler.class);
            if (ssl == null) {
                return Collections.emptyList();
            }
            try {
                Certificate[] certificates = ssl.engine().getSession().getPeerCertificates();
                if (certificates == null) {
                    return Collections.emptyList();
                }
                List<Object> result = new ArrayList<>();
                result.addAll(Arrays.asList(certificates));
                return result;
            } catch (SSLPeerUnverifiedException err) {
                return Collections.emptyList();
            }
        }

        @Override
        public void disconnect() {
            Channel c = channel;
            if (c != null) {
                c.close().addListener(x -> makeWritable());
            }
            LOG.info("authplugin disconnected channel {}", channel);
        }

        @Override
        public void setAuthorizedId(BookKeeperPrincipal principal) {
            authorizedId = principal;
            LOG.info("connection {} authenticated as {}", channel, principal);
        }

        @Override
        public BookKeeperPrincipal getAuthorizedId() {
            return authorizedId;
        }

        @Override
        public boolean isSecure() {
            Channel c = channel;
            if (c == null) {
                return false;
            } else {
                return c.pipeline().get(SslHandler.class) != null;
            }
        }

    };
}

From source file:org.evilco.network.rcon.server.LocalRconServer.java

License:Apache License

/**
 * {@inheritDoc}
 */
@Override
public EventLoopGroup createEventLoopGroup() {
    return (new DefaultEventLoopGroup());
}