Example usage for io.netty.bootstrap Bootstrap Bootstrap

List of usage examples for io.netty.bootstrap Bootstrap Bootstrap

Introduction

In this page you can find the example usage for io.netty.bootstrap Bootstrap Bootstrap.

Prototype

public Bootstrap() 

Source Link

Usage

From source file:WorldClockClient.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*w  w  w. ja  v a  2  s .c o 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();
        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 {/*  w w  w  .j ava  2  s.c  om*/
        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: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() {
    });//  ww  w .  jav  a  2s  .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) {// www . j  a  va 2s .  com
        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:MultiThreadClient.java

License:Apache License

public void run() throws Exception {
    try {//from ww w  . j  a v  a2 s  .c  o  m
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelDuplexHandler() {
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        System.out.println(
                                index + "-??:" + msg + "Read:" + Thread.currentThread());
                    }

                    @Override
                    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
                            throws Exception {
                        ChannelFuture future = ctx.writeAndFlush(msg, promise);
                        System.out.println(index + "-Write:" + Thread.currentThread());
                        Thread.yield();
                        Thread.yield();
                        future.addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                                System.out.println(index + "-Listener" + "Lintener:"
                                        + Thread.currentThread());
                            }
                        });
                    }
                });

        // Make the connection attempt.
        ChannelFuture f = b.connect(host, port).sync();
        for (int i = 0; i < 10; i++) {
            f.channel().writeAndFlush(Unpooled.wrappedBuffer(new byte[10]));
        }
        // Wait until the connection is closed.

        f.channel().closeFuture();
    } finally {
        //group.shutdownGracefully();
    }
}

From source file:Http2Client.java

License:Apache License

public Http2Client(final String host, final int port, final boolean ssl) throws Exception {
    this.host = host;
    this.port = port;
    this.ssl = ssl;

    // Configure SSL.
    if (ssl) {//from  ww w.ja  v a2 s  .  c  o  m
        this.sslCtx = SslContext.newClientContext(null, InsecureTrustManagerFactory.INSTANCE, null,
                Arrays.asList(SelectedProtocol.HTTP_2.protocolName(), SelectedProtocol.HTTP_1_1.protocolName()),
                0, 0);
    } else {
        this.sslCtx = null;
    }

    // XXX (dano): Http2Connection does not seem to be thread safe, use one thread only
    this.workerGroup = new NioEventLoopGroup(1);
    Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx);

    // Configure the client.
    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.remoteAddress(host, port);
    b.handler(initializer);

    // Start the client.
    this.channel = b.connect().syncUninterruptibly().channel();
    System.out.println("Connected to [" + host + ':' + port + ']');

    // Wait for the HTTP/2 upgrade to occur.
    this.connectionHandler = initializer.connectionHandler();
    connectionHandler.awaitInitialization();
}

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 {/*w  w w.  ja  v  a 2 s .c  o  m*/
        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:NettyHttpTransportSourceHandler.java

License:Apache License

/**
 * activating registered handler to accept events.
 *
 * @param ctx/*  w w  w .j  a  va 2 s . c  om*/
 * @throws Exception
 */
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {

    final Channel inboundChannel = ctx.channel();

    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass());
    b.handler(new NettyTargetHandlerInitilizer(inboundChannel)).option(ChannelOption.AUTO_READ, false);

    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000);

    b.option(ChannelOption.SO_SNDBUF, 1048576);
    b.option(ChannelOption.SO_RCVBUF, 1048576);

    ChannelFuture f = b.connect(NettyHttpListner.HOST, NettyHttpListner.HOST_PORT);

    outboundChannel = f.channel();
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();
            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });

}

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 {/*from  w  w w .  ja va  2s.  co 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 {// ww w  .  j  a v a2s  .  co  m
        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 {

    }
}