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:WorldClockClient.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*from   www . j ava2 s . c  om*/
        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();
        group.shutdownGracefully();
        /*
         // 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();
    }
}

From source file:UdpServer.java

License:Open Source License

public void run() throws Exception {
    final NioEventLoopGroup group = new NioEventLoopGroup();
    //Create Actor System
    final ActorSystem system = ActorSystem.create("CapwapFSMActorSystem");
    final ActorRef PacketProcessorActor = system
            .actorOf(Props.create(CapwapMsgProcActor.class, "MessageProcessorActor"), "MessageProcessorActor");
    try {/*from www. jav  a  2s.c  o  m*/
        final Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChannelInitializer<NioDatagramChannel>() {
                    @Override
                    public void initChannel(final NioDatagramChannel ch) throws Exception {

                        ChannelPipeline p = ch.pipeline();
                        createActorAndHandler(p);
                        //p.addLast(new IncommingPacketHandler(PacketProcessorActor));
                    }
                });

        // Bind and start to accept incoming connections.
        Integer pPort = port;
        InetAddress address = InetAddress.getLoopbackAddress();
        System.out.printf("\n\nwaiting for message %s %s\n\n", String.format(pPort.toString()),
                String.format(address.toString()));
        b.bind(address, port).sync().channel().closeFuture().await();

    } finally {
        System.out.print("In Server Finally");
    }
}

From source file:WorldClockServer.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//www. j  av a 2  s.c o m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new WorldClockServerInitializer());

        b.bind(port).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:NettyBootSpeedTest.java

@Test
public void testBoot() throws InterruptedException {
    long start = System.currentTimeMillis();

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.group(new NioEventLoopGroup());
    bootstrap.handler(new ChannelHandlerAdapter() {
    });/*from  www  .  j a  va2s . c  o m*/

    long mid = System.currentTimeMillis();

    bootstrap.bind(10000).await();
    bootstrap.connect("localhost", 10000).await();

    long end = System.currentTimeMillis();
    System.out.println("Setup took " + (mid - start) + " ms");
    System.out.println("Boot took " + (end - start) + " ms");
}

From source file:TelnetClient.java

License:Apache License

public static void main(String args[]) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from w  w  w . j ava 2s .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 TelnetClientInitializer(sslCtx));

        // Start the connection attempt.
        Channel ch = b.connect(HOST, PORT).sync().channel();

        // Read commands from the stdin.
        ChannelFuture lastWriteFuture = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        // Sends the received line to the server.
        while (true) {
            lastWriteFuture = ch.writeAndFlush("req" + "\r\n");
        }

        // If user typed the 'bye' command, wait until the server closes
        // the connection.

        // ch.closeFuture().sync();

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

From source file:HttpUploadServer.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*w  w w  . j a va2  s .  c o m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new HttpUploadServerInitializer());

        Channel ch = b.bind(port).sync().channel();
        System.out.println("HTTP Upload Server at port " + port + '.');
        System.out.println("Open your browser and navigate to http://localhost:" + port + '/');

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

From source file:HttpUploadClient.java

License:Apache License

public void run() throws Exception {
    String postSimple, postFile, get;
    if (baseUri.endsWith("/")) {
        postSimple = baseUri + "formpost";
        postFile = baseUri + "formpostmultipart";
        get = baseUri + "formget";
    } else {/*from w w  w. j  a v a 2s  . c om*/
        postSimple = baseUri + "/formpost";
        postFile = baseUri + "/formpostmultipart";
        get = baseUri + "/formget";
    }
    URI uriSimple;
    try {
        uriSimple = new URI(postSimple);
    } catch (URISyntaxException e) {
        logger.log(Level.WARNING, "Invalid URI syntax", e);
        return;
    }
    String scheme = uriSimple.getScheme() == null ? "http" : uriSimple.getScheme();
    String host = uriSimple.getHost() == null ? "localhost" : 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)) {
        logger.log(Level.WARNING, "Only HTTP(S) is supported.");
        return;
    }

    boolean ssl = "https".equalsIgnoreCase(scheme);

    URI uriFile;
    try {
        uriFile = new URI(postFile);
    } catch (URISyntaxException e) {
        logger.log(Level.WARNING, "Error: ", e);
        return;
    }
    File file = new File(filePath);
    if (!file.canRead()) {
        logger.log(Level.WARNING, "A correct path is needed");
        return;
    }

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

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

        // Simple Post form: factory used for big attributes
        List<InterfaceHttpData> bodylist = formPost(b, host, port, uriSimple, file, factory, headers);
        if (bodylist == null) {
            factory.cleanAllHttpDatas();
            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.cleanAllHttpDatas();
    }
}

From source file:FSMTester.java

License:Open Source License

public void run() throws Exception {
    final NioEventLoopGroup group = new NioEventLoopGroup();
    //Create Actor System
    final ActorSystem system = ActorSystem.create("CapwapFSMActorSystem");
    final ActorRef PacketProcessorActor = system
            .actorOf(Props.create(CapwapMsgProcActor.class, "MessageProcessorActor"), "MessageProcessorActor");
    try {/* www .  jav a 2s  .c  o  m*/
        final Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChannelInitializer<NioDatagramChannel>() {
                    @Override
                    public void initChannel(final NioDatagramChannel ch) throws Exception {

                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new IncommingPacketFSMHandler(PacketProcessorActor));
                    }
                });

        // Bind and start to accept incoming connections.
        Integer pPort = port;
        InetAddress address = InetAddress.getLoopbackAddress();
        System.out.printf("\n\nwaiting for message %s %s\n\n", String.format(pPort.toString()),
                String.format(address.toString()));
        b.bind(address, port).sync().channel().closeFuture().await();

    } finally {
        System.out.print("In Server Finally");
    }
}

From source file:afred.javademo.proxy.rpc.ObjectEchoClient.java

License:Apache License

public void start(String host, int port) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {//  www.  j av  a2  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 {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                        new ObjectEchoClientHandler());
            }
        });

        channel = b.connect(host, port).sync().channel();
    } finally {

    }
}

From source file:at.yawk.accordion.netty.NettyConnector.java

License:Mozilla Public License

@Override
public Optional<Connection> connect(SocketAddress address) {
    // TODO find a non-hacky method to close channels
    Collection<Channel> registeredChannels = Collections.synchronizedList(new ArrayList<>());

    EventLoopGroup workerGroup = new NioEventLoopGroup() {
        @Override//from   w ww. ja va 2s  .c o  m
        public ChannelFuture register(Channel channel, ChannelPromise promise) {
            registeredChannels.add(channel);
            return super.register(channel, promise);
        }
    };

    AtomicReference<Connection> connectionRef = new AtomicReference<>();

    // init
    Bootstrap bootstrap = new Bootstrap().group(workerGroup).handler(new ChannelHandlerAdapter() {
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            NettyConnection connection = new NettyConnection(ctx.channel());
            connectionRef.set(connection);
            connection.init();
        }
    }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true);

    try {
        // connect
        ChannelFuture connectFuture = bootstrap.connect(address);
        // wait for connection
        connectFuture.sync();
        return Optional.of(connectionRef.get());
    } catch (Exception e) {
        // shut down workers
        workerGroup.shutdownGracefully();

        // kill channels
        registeredChannels.forEach(NettyConnection::close);

        return Optional.empty();
    }
}