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:cloudeventbus.client.EventBusImpl.java

License:Open Source License

EventBusImpl(Connector connector) {
    if (connector.servers.size() == 0) {
        throw new IllegalArgumentException("No servers were specified to connect to.");
    }// www.  ja v a  2  s.c  om

    id = connector.id;

    servers.addServers(connector.servers);
    autoReconnect = connector.autoReconnect;
    reconnectWaitTime = connector.reconnectWaitTime;

    shutDownEventLoop = connector.eventLoopGroup == null;
    eventLoopGroup = shutDownEventLoop ? new NioEventLoopGroup() : connector.eventLoopGroup;
    maxMessageSize = connector.maxMessageSize;

    certificateChain = connector.certificateChain;
    privateKey = connector.privateKey;
    trustStore = connector.trustStore;

    listeners = new ArrayList<>(connector.listeners);

    executor = connector.callbackExecutor;

    connect();
}

From source file:club.jmint.crossing.client.CrossingClient.java

License:Apache License

public void startup() throws CrossException {
    SslContext sslCtx = null;/*w  w  w  .  j av a2s.c o  m*/
    if (isSSLEnabled) {
        try {
            sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        } catch (Exception e) {
            CrossLog.printStackTrace(e);
            throw new CrossException(ErrorCode.CROSSING_ERR_CLIENT_STARTUP.getCode(),
                    ErrorCode.CROSSING_ERR_CLIENT_STARTUP.getInfo());
        }
    } else {
        sslCtx = null;
    }

    // Configure the client.
    group = new NioEventLoopGroup();
    try {
        bs = new Bootstrap();
        bs.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ClientChannelInitializer(sslCtx, chandler));

        // Start the client.
        cf = bs.connect(ip, port).sync();
        channel = cf.channel();

        // Wait until the connection is closed.
        //f.channel().closeFuture().sync();
    } catch (Exception e) {
        CrossLog.printStackTrace(e);
        throw new CrossException(ErrorCode.CROSSING_ERR_CLIENT_STARTUP.getCode(),
                ErrorCode.CROSSING_ERR_CLIENT_STARTUP.getInfo());

        //System.exit(-1);;
    } finally {
        // Shut down the event loop to terminate all threads.
        //group.shutdownGracefully();
    }

    ccall = new CrossingCall(cf, chandler, config);
    CrossLog.logger.info("Crossing Client started.");
}

From source file:club.lovety.xy.netty.test.UptimeClient.java

License:Apache License

private static Bootstrap configureBootstrap(Bootstrap b) {
    return configureBootstrap(b, new NioEventLoopGroup());
}

From source file:cn.ac.iscas.pebble.open.dc.nettyClient.NettyOracleClientPassRecord.java

public void operateOnTime() {
    TimerTask task = new TimerTask() {
        @Override/*w ww. ja va  2  s . c om*/
        public void run() {
            // TODO Auto-generated method stub
            EventLoopGroup group = new NioEventLoopGroup();
            int result = 0;
            try {
                Bootstrap b = new Bootstrap();
                b.group(group).channel(NioSocketChannel.class).handler(new nettyClientInitializer());

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

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

                //read mid file
                File file = new File(logMidFile);
                BufferedReader reader = null;
                Date dateStart = cc.getTime();
                String tmpString;
                try {
                    reader = new BufferedReader(new FileReader(file));
                    while ((tmpString = reader.readLine()) != null && tmpString.equals("") == false) {
                        Date dateTmp = sdf.parse(tmpString);
                        if (dateStart.compareTo(dateTmp) < 0)
                            dateStart = dateTmp;
                    }
                    System.out.println("start time from log file:" + dateStart);
                    //                     System.out.println("end time:"+dateEnd);
                } catch (IOException e) {
                    //e.printStackTrace();
                    System.out.println("IO/logPassRecord.txt" + " is not exit.");
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
                //set start and end time
                cc.setTime(dateStart);
                dataStartTime = sdf.format(cc.getTime());
                int min = cc.get(Calendar.MINUTE);
                cc.set(Calendar.MINUTE, min + intervalTime);
                dataEndTime = sdf.format(cc.getTime());

                //clean data
                CleanDataRealtime cleanDataRealtime = new CleanDataRealtime(propPathClean);
                cleanDataRealtime.setDataStartTime(dataStartTime);
                cleanDataRealtime.setDataEndTime(dataEndTime);
                cleanDataRealtime.cleanDataRealtime();
                mapCleanNetty = cleanDataRealtime.getMapClean();
                if (mapCleanNetty == null)
                    System.out.println("mapCleanNetty null");
                else
                    result = cleanAndSend(handler); // Request and get the response.
                // Close the connection.
                ch.close();

                //write txt file
                WriteTxtRealtime writeTxtRealtime = new WriteTxtRealtime();
                writeTxtRealtime.setMapCleanTxt(mapCleanNetty);
                writeTxtRealtime.setTxtFilePath(txtFileRootPath);
                writeTxtRealtime.setStrDateBegin(dataStartTime);
                writeTxtRealtime.WriteTxtRealtime();

            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                group.shutdownGracefully();
            }

            if (result != 0) {
                try {
                    throw new Exception("send data fail.");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    };

    Timer timer = new Timer();
    timer.schedule(task, cc.getTime(), intervalTime * 60 * 1000);
}

From source file:cn.ac.iscas.pebble.open.dc.nettyClient.nettyOracleClientPassRecordRealtime.java

public void operateOnTime() {
    TimerTask task = new TimerTask() {
        @Override/*w ww  .j  a va2 s .  com*/
        public void run() {
            // TODO Auto-generated method stub
            EventLoopGroup group = new NioEventLoopGroup();
            int result = 0;
            try {
                Bootstrap b = new Bootstrap();
                b.group(group).channel(NioSocketChannel.class).handler(new nettyClientInitializer());

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

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

                //read mid file
                File file = new File("IO/logMidPassRecordData.txt");
                BufferedReader reader = null;
                Date dateStart = cc.getTime();
                String tmpString;
                try {
                    reader = new BufferedReader(new FileReader(file));
                    while ((tmpString = reader.readLine()) != null && tmpString.equals("") == false) {
                        Date dateTmp = sdf.parse(tmpString);
                        if (dateStart.compareTo(dateTmp) < 0)
                            dateStart = dateTmp;
                    }
                    System.out.println("start time from log file:" + dateStart);
                    //                     System.out.println("end time:"+dateEnd);
                } catch (IOException e) {
                    //e.printStackTrace();
                    System.out.println("IO/logPassRecord.txt" + " is not exit.");
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
                //set start and end time
                cc.setTime(dateStart);
                dataStartTime = sdf.format(cc.getTime());
                int min = cc.get(Calendar.MINUTE);
                cc.set(Calendar.MINUTE, min + 2);
                dataEndTime = sdf.format(cc.getTime());

                //clean data
                String propPath = "src/cn/ac/iscas/pebble/open/dc/cleanData/propPassRecordClean.properties";
                //                String DataStartTime = "2013-10-02 00:00:00";
                //                String DataEndTime = "2013-10-02 00:35:00";
                //                  String propPath = "src/cn/ac/iscas/pebble/propPassRecordClean.properties";
                CleanDataRealtime cleanDataRealtime = new CleanDataRealtime(propPath);
                cleanDataRealtime.setDataStartTime(dataStartTime);
                cleanDataRealtime.setDataEndTime(dataEndTime);
                cleanDataRealtime.cleanDataRealtime();
                mapCleanNetty = cleanDataRealtime.getMapClean();
                if (mapCleanNetty == null)
                    System.out.println("mapCleanNetty null");
                // Request and get the response.
                result = readDBandSend(handler);
                // Close the connection.
                ch.close();

                //write txt file
                WriteTxtRealtime writeTxtRealtime = new WriteTxtRealtime();
                writeTxtRealtime.setMapCleanTxt(mapCleanNetty);
                writeTxtRealtime.setTxtFilePath("/oracledisk");
                writeTxtRealtime.setStrDateBegin(dataStartTime);
                writeTxtRealtime.WriteTxtRealtime();

            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                group.shutdownGracefully();
            }

            if (result != 0) {
                try {
                    throw new Exception("send data fail.");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    };

    Timer timer = new Timer();
    timer.schedule(task, cc.getTime(), 2 * 60 * 1000);
}

From source file:cn.david.main.EchoClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {// w  ww .  j a va 2 s.c om
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } 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 {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                        }
                        //p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new EchoClientHandler());
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // 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:cn.dennishucd.nettyhttpserver.HttpServer.java

License:Apache License

public void start(String host, int port) throws Exception {
    //create a reactor thread pool for NIO acceptor
    EventLoopGroup bossGroup = new NioEventLoopGroup();

    //create a reactor thread pool for NIO handler
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {/*  w w  w  .j a  v  a2 s.  c o m*/
        ServerBootstrap b = new ServerBootstrap();

        b.option(ChannelOption.SO_BACKLOG, 1024);

        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new PushServerInitializer());

        ChannelFuture f = b.bind(host, port).sync();

        logger.info("The http server is started on " + host + ":" + port);

        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:cn.npt.net.websocket.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 ? "192.168.20.71" : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if ("ws".equalsIgnoreCase(scheme)) {
            port = 80;/*  ww w. j a v  a 2s  .co 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 BaseWebSocketClientHandler handler = new EchoWebSocketClientHandler(
                WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false,
                        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), 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();
    }
}

From source file:cn.pengj.udpdemo.EchoServer.java

License:Open Source License

public static void main(String[] args) throws InterruptedException {
    Bootstrap b = new Bootstrap();
    EventLoopGroup group = new NioEventLoopGroup();
    b.group(group).channel(NioDatagramChannel.class)
            //         .option(ChannelOption.SO_BROADCAST, true)
            .handler(new EchoSeverHandler());

    // ??9999?/*  w  ww .j  av  a  2 s . c  o m*/
    b.bind(9999).sync().channel().closeFuture().await();
}

From source file:cn.wcl.test.netty.HttpUploadClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    String postSimple, postFile, get;
    if (BASE_URL.endsWith("/")) {
        postSimple = BASE_URL + "formpost";
        postFile = BASE_URL + "formpostmultipart";
        get = BASE_URL + "formget";
    } else {/*from   w  w  w  .j  a v  a2 s  . co m*/
        postSimple = BASE_URL + "/formpost";
        postFile = BASE_URL + "/formpostmultipart";
        get = BASE_URL + "/formget";
    }

    URI uriSimple = new URI(postSimple);
    String scheme = uriSimple.getScheme() == null ? "http" : uriSimple.getScheme();
    String host = uriSimple.getHost() == null ? "127.0.0.1" : uriSimple.getHost();
    int port = uriSimple.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

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

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

    URI uriFile = new URI(postFile);
    File file = new File(FILE);
    if (!file.canRead()) {
        throw new FileNotFoundException(FILE);
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();

    // setup the factory: here using a mixed memory/disk based on size threshold
    HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if MINSIZE exceed

    DiskFileUpload.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
    DiskFileUpload.baseDirectory = null; // system temp directory
    DiskAttribute.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
    DiskAttribute.baseDirectory = null; // system temp directory

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

        // Simple Get form: no factory used (not usable)
        List<Entry<String, String>> headers = formget(b, host, port, get, uriSimple);
        if (headers == null) {
            factory.cleanAllHttpData();
            return;
        }

        // Simple Post form: factory used for big attributes
        List<InterfaceHttpData> bodylist = formpost(b, host, port, uriSimple, file, factory, headers);
        if (bodylist == null) {
            factory.cleanAllHttpData();
            return;
        }

        // Multipart Post form: factory used
        formpostmultipart(b, host, port, uriFile, factory, headers, bodylist);
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();

        // Really clean all temporary files if they still exist
        factory.cleanAllHttpData();
    }
}