Example usage for io.netty.bootstrap Bootstrap connect

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

Introduction

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

Prototype

public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) 

Source Link

Document

Connect a Channel to the remote peer.

Usage

From source file:WorldClockClient.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {// w  w w .ja v a2s  .  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: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 . j ava  2 s . c  om

    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) {//  w ww.  j a va2  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 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  www  . ja v a2  s  .  co  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:HttpUploadClient.java

License:Apache License

/**
 * Standard usage of HTTP API in Netty without file Upload (get is not able to achieve File upload due to limitation
 * on request size).//  www .java 2 s  . c om
 *
 * @return the list of headers that will be used in every example after
 **/
private static List<Entry<String, String>> formGet(Bootstrap bootstrap, String host, int port, String get,
        URI uriSimple) throws Exception {
    // Start the connection attempt.
    // No use of HttpPostRequestEncoder since not a POST
    Channel channel = bootstrap.connect(host, port).sync().channel();

    // Prepare the HTTP request.
    QueryStringEncoder encoder = new QueryStringEncoder(get);
    // add Form attribute
    encoder.addParam("getform", "GET");
    encoder.addParam("info", "first value");
    encoder.addParam("secondinfo", "secondvalue &");
    // not the big one since it is not compatible with GET size
    // encoder.addParam("thirdinfo", textArea);
    encoder.addParam("thirdinfo", "third value\r\ntest second line\r\n\r\nnew line\r\n");
    encoder.addParam("Send", "Send");

    URI uriGet;
    try {
        uriGet = new URI(encoder.toString());
    } catch (URISyntaxException e) {
        logger.log(Level.WARNING, "Error: ", e);
        return null;
    }

    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
            uriGet.toASCIIString());
    HttpHeaders headers = request.headers();
    headers.set(HttpHeaders.Names.HOST, host);
    headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    headers.set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP + ',' + HttpHeaders.Values.DEFLATE);

    headers.set(HttpHeaders.Names.ACCEPT_CHARSET, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    headers.set(HttpHeaders.Names.ACCEPT_LANGUAGE, "fr");
    headers.set(HttpHeaders.Names.REFERER, uriSimple.toString());
    headers.set(HttpHeaders.Names.USER_AGENT, "Netty Simple Http Client side");
    headers.set(HttpHeaders.Names.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

    headers.set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo"),
            new DefaultCookie("another-cookie", "bar")));

    // send request
    List<Entry<String, String>> entries = headers.entries();
    channel.write(request).sync();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();

    return entries;
}

From source file:HttpUploadClient.java

License:Apache License

/**
 * Standard post without multipart but already support on Factory (memory management)
 *
 * @return the list of HttpData object (attribute and file) to be reused on next post
 *///from   ww  w .  j a  v a 2 s .co  m
private static List<InterfaceHttpData> formPost(Bootstrap bootstrap, String host, int port, URI uriSimple,
        File file, HttpDataFactory factory, List<Entry<String, String>> headers) throws Exception {

    // Start the connection attempt
    Channel channel = bootstrap.connect(host, port).sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            uriSimple.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder = null;
    try {
        bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, false); // false not multipart
    } catch (NullPointerException e) {
        // should not be since args are not null
        e.printStackTrace();
    } catch (ErrorDataEncoderException e) {
        // test if getMethod is a POST getMethod
        e.printStackTrace();
    }

    // it is legal to add directly header or cookie into the request until finalize
    for (Entry<String, String> entry : headers) {
        request.headers().set(entry.getKey(), entry.getValue());
    }

    // add Form attribute
    try {
        bodyRequestEncoder.addBodyAttribute("getform", "POST");
        bodyRequestEncoder.addBodyAttribute("info", "first value");
        bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue &");
        bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea);
        bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false);
        bodyRequestEncoder.addBodyAttribute("Send", "Send");
    } catch (NullPointerException e) {
        // should not be since not null args
        e.printStackTrace();
    } catch (ErrorDataEncoderException e) {
        // if an encoding error occurs
        e.printStackTrace();
    }

    // finalize request
    try {
        request = bodyRequestEncoder.finalizeRequest();
    } catch (ErrorDataEncoderException e) {
        // if an encoding error occurs
        e.printStackTrace();
    }

    // Create the bodylist to be reused on the last version with Multipart support
    List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes();

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) {
        // could do either request.isChunked()
        // either do it through ChunkedWriteHandler
        channel.write(bodyRequestEncoder).awaitUninterruptibly();
    }

    // Do not clear here since we will reuse the InterfaceHttpData on the
    // next request
    // for the example (limit action on client side). Take this as a
    // broadcast of the same
    // request on both Post actions.
    //
    // On standard program, it is clearly recommended to clean all files
    // after each request
    // bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();

    return bodylist;
}

From source file:HttpUploadClient.java

License:Apache License

/**
 * Multipart example/*w ww  . ja v a2 s  .c om*/
 */
private static void formPostMultipart(Bootstrap bootstrap, String host, int port, URI uriFile,
        HttpDataFactory factory, List<Entry<String, String>> headers, List<InterfaceHttpData> bodylist)
        throws Exception {

    // Start the connection attempt
    Channel channel = bootstrap.connect(host, port).sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            uriFile.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder = null;
    try {
        bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, true); // true => multipart
    } catch (NullPointerException e) {
        // should not be since no null args
        e.printStackTrace();
    } catch (ErrorDataEncoderException e) {
        // test if getMethod is a POST getMethod
        e.printStackTrace();
    }

    // it is legal to add directly header or cookie into the request until finalize
    for (Entry<String, String> entry : headers) {
        request.headers().set(entry.getKey(), entry.getValue());
    }

    // add Form attribute from previous request in formpost()
    try {
        bodyRequestEncoder.setBodyHttpDatas(bodylist);
    } catch (NullPointerException e1) {
        // should not be since previously created
        e1.printStackTrace();
    } catch (ErrorDataEncoderException e1) {
        // again should not be since previously encoded (except if an error
        // occurs previously)
        e1.printStackTrace();
    }

    // finalize request
    try {
        request = bodyRequestEncoder.finalizeRequest();
    } catch (ErrorDataEncoderException e) {
        // if an encoding error occurs
        e.printStackTrace();
    }

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) {
        channel.write(bodyRequestEncoder).awaitUninterruptibly();
    }

    // Now no more use of file representation (and list of HttpData)
    bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();
}

From source file:NettyHttpTransportSourceHandler.java

License:Apache License

/**
 * activating registered handler to accept events.
 *
 * @param ctx//w  ww .  ja  v a2s . com
 * @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:afred.javademo.proxy.rpc.ObjectEchoClient.java

License:Apache License

public void start(String host, int port) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {//from   ww  w  .j av  a  2s.  c o 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 {

    }
}

From source file:basic.TimeClient.java

License:Apache License

public void connect(int port, String host) throws Exception {
    // ?NIO/*  ww  w. j av a2 s . com*/
    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 TimeClientHandler());
                    }
                });

        // ??
        ChannelFuture f = b.connect(host, port).sync();
        // 
        f.channel().closeFuture().sync();
    } finally {
        // NIO
        group.shutdownGracefully();
    }
}