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.gdut.Netty_testing.dongjun.client.Client.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from w  ww . j a  v  a 2  s.  c  o  m*/
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ClientInitializer(sslCtx));

        // Make a new connection.
        Channel ch = b.connect(HOST, PORT).sync().channel();
        ch.writeAndFlush("108B01008C163543653432532432");

        // Get the handler instance to initiate the request.
        //            ClientHandler handler = ch.pipeline().get(ClientHandler.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.
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.gdut.Netty_testing.t2.client.WorldClockClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/* w  w  w. j ava  2 s  . co m*/
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new WorldClockClientInitializer(sslCtx));

        // 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);

        for (int j = 0; j < 6; j++) {

            // Request and get the response.
            List<String> response = handler.getLocalTimes(CITIES);
            Thread.sleep(2000);

            // Print the response at last but not least.
            for (int i = 0; i < CITIES.size(); i++) {
                System.out.format("%28s: %s%n", CITIES.get(i), response.get(i));
            }
        }
        // Close the connection.
        ch.close();

    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.gdut.Netty_testing.time_server.client.TimeClient.java

License:Apache License

/**
 * /* ww  w  .  j  av  a2 s. c  o m*/
 * @Title: main
 * @Description: TODO
 * @param @param args
 * @param @throws Exception
 * @return void
 * @throws
 */
public static void main(String[] args) throws Exception {
    // Configure SSL.git
    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).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new TimeDecoder(), new TimeClientHandler(),
                                new TimeOutBoundHandler(), new LoggingHandler(LogLevel.INFO));
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT).sync();
        // channel.connect(remoteAddress, promise);
        // ?connect()??OutboundHandler
        // ?InboundHandlerlogic???
        // ??
        // InboundHandler?writeAndFlush(Object
        // msg)??OutBoundHandler
        // ??  ctx.write(encoded, promise);
        // writeAndFlush(Object msg)
        // ?InboundHandler  decoder?
        // ?TimeClientHandler()Handler,
        // ctx.close();?OutBoundHandler ?

        Thread.sleep(9000);
        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:com.github.brandtg.switchboard.FileLogAggregator.java

License:Apache License

/**
 * An agent that aggregates logs from multiple sources and multiplexes them.
 *
 * @param sources//from   w w w.j ava 2 s .  c o  m
 *  A set of source switchboard servers from which to pull logs
 * @param separator
 *  The line delimiter (after this is reached, lines will be output to outputStream)
 * @param outputStream
 *  OutputStream to which all multiplexed logs are piped
 */
public FileLogAggregator(Set<InetSocketAddress> sources, char separator, OutputStream outputStream)
        throws IOException {
    this.separator = separator;
    this.outputStream = outputStream;
    this.isShutdown = new AtomicBoolean(true);
    this.eventExecutors = new NioEventLoopGroup();
    this.logReceivers = new HashMap<>();
    this.inputStreams = new HashMap<>();
    this.listener = new Object();
    this.muxExecutor = Executors.newSingleThreadExecutor();
    this.stringBuffers = new HashMap<>();

    for (InetSocketAddress source : sources) {
        PipedOutputStream pos = new PipedOutputStream();
        PipedInputStream pis = new PipedInputStream(pos);
        LogReceiver logReceiver = new LogReceiver(new InetSocketAddress(0), eventExecutors, pos);
        logReceiver.registerListener(listener);
        logReceivers.put(source, logReceiver);
        inputStreams.put(source, pis);
        stringBuffers.put(source, new StringBuffer());
    }
}

From source file:com.github.brandtg.switchboard.HdfsLogIterator.java

License:Apache License

/**
 * Process listens to edit log events and prints their toString to STDOUT.
 */// w  w  w  . j ava2s. com
public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        throw new Exception("usage: sourceHost:sourcePort serverPort");
    }
    String[] sourceHostPort = args[0].split(":");
    InetSocketAddress sourceAddress = new InetSocketAddress(sourceHostPort[0],
            Integer.valueOf(sourceHostPort[1]));
    InetSocketAddress serverAddress = new InetSocketAddress(Integer.valueOf(args[1]));
    PipedOutputStream outputStream = new PipedOutputStream();

    final EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    final LogReceiver logReceiver = new LogReceiver(serverAddress, eventLoopGroup, outputStream);
    final LogPuller logPuller = new LogPuller(sourceAddress, serverAddress, "*", 0);
    final ExecutorService pullerExecutor = Executors.newSingleThreadExecutor();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                logPuller.shutdown();
                pullerExecutor.shutdown();
                logReceiver.shutdown();
            } catch (Exception e) {
                LOG.error("Exception while shutting down log receiver", e);
            }
            eventLoopGroup.shutdownGracefully();
        }
    });

    logReceiver.registerListener(logPuller);
    logReceiver.start();
    pullerExecutor.submit(logPuller);

    // Print edit log ops to console
    PipedInputStream inputStream = new PipedInputStream(outputStream, 1024 * 1024);
    LogIterator<FSEditLogOp> itr = new HdfsLogIterator(inputStream);
    while (itr.hasNext()) {
        System.out.println(itr.next());
    }
}

From source file:com.github.brandtg.switchboard.LogReceiver.java

License:Apache License

public static void main(String[] args) throws Exception {
    LogReceiver logReceiver = new LogReceiver(new InetSocketAddress(2000), new NioEventLoopGroup(), System.out);
    logReceiver.start();//from w  ww. j ava 2s  . c o m
}

From source file:com.github.brandtg.switchboard.MysqlLogPuller.java

License:Apache License

/**
 * Starts pulling events from switchboard server.
 *//*from  ww  w  .  ja  v  a 2 s .c o m*/
public void start() throws Exception {
    if (!isStarted.getAndSet(true)) {
        outputStream.connect(inputStream);

        callbackExecutor = Executors.newSingleThreadExecutor();
        refreshExecutor = Executors.newSingleThreadExecutor();
        eventExecutors = new NioEventLoopGroup();

        // Start server to receive log segments
        logReceiver = new LogReceiver(sinkAddress, eventExecutors, outputStream);
        logReceiver.start();

        // Iterates through events and fires appropriate callbacks
        callbackExecutor.submit(getCallback());

        // Pulls log indexes
        logPuller = new LogPuller(sourceAddress, sinkAddress, database, lastIndex);
        logReceiver.registerListener(logPuller);
        refreshExecutor.submit(logPuller);
    }
}

From source file:com.github.herong.rpc.netty.protobuf.demo1.ProtobufClient.java

License:Apache License

public void run() throws Exception {
    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*  ww  w. ja  v  a2 s .  c  o m*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()

                                // 
                                .addLast("frameDecoder", new ProtobufVarint32FrameDecoder())
                                // 
                                .addLast("protobufDecoder",
                                        new ProtobufDecoder(AddressBookProtos.AddressBook.getDefaultInstance()))
                                // 
                                .addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender())
                                .addLast("protobufEncoder", new ProtobufEncoder())
                                // 
                                .addLast("handler", new ProtobufClientHandler());

                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(host, port).sync();

        sendMsg(f.channel());
        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:com.github.herong.rpc.netty.protobuf.demo2.Demo2ProtobufClient.java

License:Apache License

public void run() throws Exception {
    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {//w  w  w . ja  v a2 s  .  c om
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()

                                // 
                                .addLast("frameDecoder", new ProtobufVarint32FrameDecoder())
                                // 
                                .addLast("protobufDecoder",
                                        new ProtobufDecoder(Message.DTO.getDefaultInstance()))
                                // 
                                .addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender())
                                .addLast("protobufEncoder", new ProtobufEncoder())
                                // 
                                .addLast("handler", new Demo2ProtobufClientHandler());

                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(host, port).sync();

        sendMsg(f.channel());
        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}

From source file:com.github.lburgazzoli.quickfixj.transport.netty.NettySocketInitiator.java

License:Apache License

/**
 *
 *//*w ww  . j a  v a2s .c o  m*/
@Override
public void connect() {
    try {
        m_boot = new Bootstrap();
        m_boot.group(new NioEventLoopGroup());
        m_boot.channel(NioSocketChannel.class);
        m_boot.option(ChannelOption.SO_KEEPALIVE, true);
        m_boot.option(ChannelOption.TCP_NODELAY, true);
        m_boot.option(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true));
        m_boot.handler(new NettyChannelInitializer(this, getHelper(), FIXSessionType.INITIATOR));

        getHelper().getSession().getSessionID();
        String host = getHelper().getSettings().getString("SocketConnectHost");
        int port = getHelper().getSettings().getInt("SocketConnectPort");

        m_boot.remoteAddress(new InetSocketAddress(host, port));

        if (!isRunning()) {
            setRunning(true);
            doConnect();
        }
    } catch (Exception e) {
        LOGGER.warn("Exception", e);
        setRunning(false);
    }
}