List of usage examples for io.netty.channel ChannelFuture sync
@Override
ChannelFuture sync() throws InterruptedException;
From source file:dpfmanager.shell.modules.client.upload.HttpClient.java
License:Open Source License
/** * Multipart POST/* w w w . j ava 2 s.c om*/ */ private void formpostmultipart(Bootstrap bootstrap, String host, int port, URI uriFile, HttpDataFactory factory) throws Exception { // Start the connection attempt. ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); Channel channel = future.sync().channel(); // Prepare the HTTP request. HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriFile.toASCIIString()); // Use the PostBody encoder HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, true); HttpHeaders headers = request.headers(); headers.set(HttpHeaderNames.HOST, host); headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); // Add the files int i = 0; for (File file : files) { bodyRequestEncoder.addBodyFileUpload("file" + i, file, "image/tiff", false); i++; } for (File file : tmpFiles) { bodyRequestEncoder.addBodyFileUpload("file" + i, file, "image/tiff", false); i++; } // Add configuration if (config != null) { bodyRequestEncoder.addBodyFileUpload("config", config, "application/octet-stream", false); } // Add job id if (id != null) { bodyRequestEncoder.addBodyAttribute("id", id); } // finalize request bodyRequestEncoder.finalizeRequest(); // send request channel.write(request); // test if request was chunked and if so, finish the write if (bodyRequestEncoder.isChunked()) { channel.write(bodyRequestEncoder); } channel.flush(); // 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:eu.point.client.Client.java
License:Open Source License
/** * The method which creates the bootstrap to connect to the server. * It initializes the pipeline with all the required parameters and functions * for encoding, decoding, etc.//from w ww.ja va 2 s . c o m * It then sends the message to the server. * If the message is a Resource Request, then it also returns the received Resource Offer. * * @param message The message to be sent. * @return The received Resource Offer in case the message was a Resource Request. */ public static TmSdnMessages.TmSdnMessage.ResourceOfferMessage sendMessage(TmSdnMessages.TmSdnMessage message) { EventLoopGroup group = new NioEventLoopGroup(); TmSdnMessages.TmSdnMessage.ResourceOfferMessage resourceOffer = null; handler = new TmSdnClientHandler(message); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, false); //initialize the pipeline b.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new ProtobufVarint32FrameDecoder()); pipeline.addLast(new ProtobufDecoder(TmSdnMessages.TmSdnMessage.getDefaultInstance())); pipeline.addLast(new ProtobufVarint32LengthFieldPrepender()); pipeline.addLast(new ProtobufEncoder()); pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(5)); pipeline.addLast(handler); } }); // Make a new connection. ChannelFuture f = b.remoteAddress(serverIP, tcpPort).connect(); try { f.sync(); } catch (Exception e) { e.printStackTrace(); } //if message is resource request, then get the received resource offer and return it. if (f.isSuccess() && message.getType() == TmSdnMessages.TmSdnMessage.TmSdnMessageType.RR) { TmSdnMessages.TmSdnMessage.ResourceOfferMessage resp = handler.resultQueue.take(); if (resp != null) { resourceOffer = resp; } } //close the channel. f.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } finally { group.shutdownGracefully(); } return resourceOffer; }
From source file:fixio.examples.priceclient.PriceClient.java
License:Apache License
public static void main(String[] args) throws InterruptedException { PriceClient priceClient = new PriceClient(PriceServer.DEFAULT_PORT); ChannelFuture channelFuture = priceClient.connect(); channelFuture.sync(); priceClient.shutdown();/*from w w w .j av a 2s .co m*/ }
From source file:fr.wuzuf.netty.handlers.codec.tn3270.Client.java
License:Apache License
public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {//from www . j av a2 s.c o m Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ClientInitializer()); // 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)); for (;;) { String line = in.readLine(); if (line == null) { break; } // Sends the received line to the server. lastWriteFuture = ch.writeAndFlush(line); // If user typed the 'bye' command, wait until the server closes // the connection. if ("bye".equals(line.toLowerCase())) { ch.closeFuture().sync(); break; } } // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.sync(); } } finally { group.shutdownGracefully(); } }
From source file:io.aos.netty5.memcache.binary.MemcacheClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {/*from w ww .java2 s . co m*/ sslCtx = SslContext.newClientContext(null, InsecureTrustManagerFactory.INSTANCE, null, Arrays.asList(SelectedProtocol.HTTP_2.protocolName(), SelectedProtocol.HTTP_1_1.protocolName()), 0, 0); } else { sslCtx = null; } EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT)); } p.addLast(new BinaryMemcacheClientCodec()); p.addLast(new BinaryMemcacheObjectAggregator(Integer.MAX_VALUE)); p.addLast(new MemcacheClientHandler()); } }); // Start the connection attempt. Channel ch = b.connect(HOST, PORT).sync().channel(); // Read commands from the stdin. System.out.println("Enter commands (quit to end)"); System.out.println("get <key>"); System.out.println("set <key> <value>"); ChannelFuture lastWriteFuture = null; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (;;) { String line = in.readLine(); if (line == null) { break; } if ("quit".equals(line.toLowerCase())) { ch.close().sync(); break; } // Sends the received line to the server. lastWriteFuture = ch.writeAndFlush(line); } // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.sync(); } } finally { group.shutdownGracefully(); } }
From source file:io.aos.netty5.telnet.TelnetClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {//from w ww .j av a 2 s . co m sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } 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)); for (;;) { String line = in.readLine(); if (line == null) { break; } // Sends the received line to the server. lastWriteFuture = ch.writeAndFlush(line + "\r\n"); // If user typed the 'bye' command, wait until the server closes // the connection. if ("bye".equals(line.toLowerCase())) { ch.closeFuture().sync(); break; } } // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.sync(); } } finally { group.shutdownGracefully(); } }
From source file:io.example.UploadClient.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 */// ww w . j a v a2s . c o 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 { // XXX /formpost // Start the connection attempt. ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); // Wait until the connection attempt succeeds or fails. Channel channel = future.sync().channel(); // Prepare the HTTP request. HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriSimple.toASCIIString()); // Use the PostBody encoder HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, false); // false => not multipart // 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 bodyRequestEncoder.addBodyAttribute("getform", "POST"); bodyRequestEncoder.addBodyAttribute("info", "first value"); bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue &"); bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea); bodyRequestEncoder.addBodyAttribute("fourthinfo", textAreaLong); bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false); // finalize request request = bodyRequestEncoder.finalizeRequest(); // 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); } System.out.println("Sent formpost"); channel.flush(); // 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:io.example.UploadClient.HttpUploadClient.java
License:Apache License
/** * Multipart example//from w w w .j a va 2 s . co m */ private static void formpostmultipart(Bootstrap bootstrap, String host, int port, URI uriFile, HttpDataFactory factory, List<Entry<String, String>> headers, List<InterfaceHttpData> bodylist) throws Exception { // XXX /formpostmultipart // Start the connection attempt. ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); // Wait until the connection attempt succeeds or fails. Channel channel = future.sync().channel(); // Prepare the HTTP request. HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uriFile.toASCIIString()); // Use the PostBody encoder HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, true); // true => multipart // 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() bodyRequestEncoder.setBodyHttpDatas(bodylist); // finalize request bodyRequestEncoder.finalizeRequest(); // send request channel.write(request); // test if request was chunked and if so, finish the write if (bodyRequestEncoder.isChunked()) { channel.write(bodyRequestEncoder); } System.out.println("Sent formpostmultipart"); channel.flush(); // 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:io.grpc.netty.NettyClientHandlerTest.java
License:Apache License
@Test public void nonExistentStream() throws Exception { Status status = Status.INTERNAL.withDescription("zz"); lifecycleManager.notifyShutdown(status); // Stream creation can race with the transport shutting down, with the create command already // enqueued.// w w w . ja v a2 s . c o m ChannelFuture future1 = createStream(); future1.await(); assertNotNull(future1.cause()); assertThat(Status.fromThrowable(future1.cause()).getCode()).isEqualTo(status.getCode()); ChannelFuture future2 = enqueue(new CancelClientStreamCommand(streamTransportState, status)); future2.sync(); }
From source file:io.grpc.netty.ProtocolNegotiatorsTest.java
License:Apache License
@Test public void waitUntilActiveHandler_handlerAdded() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final WaitUntilActiveHandler handler = new WaitUntilActiveHandler(new ChannelHandlerAdapter() { @Override//from www . j av a2 s .co m public void handlerAdded(ChannelHandlerContext ctx) throws Exception { assertTrue(ctx.channel().isActive()); latch.countDown(); super.handlerAdded(ctx); } }); ChannelHandler lateAddingHandler = new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.pipeline().addLast(handler); ctx.pipeline().fireUserEventTriggered(ProtocolNegotiationEvent.DEFAULT); // do not propagate channelActive(). } }; LocalAddress addr = new LocalAddress("local"); ChannelFuture cf = new Bootstrap().channel(LocalChannel.class).handler(lateAddingHandler).group(group) .register(); chan = cf.channel(); ChannelFuture sf = new ServerBootstrap().channel(LocalServerChannel.class) .childHandler(new ChannelHandlerAdapter() { }).group(group).bind(addr); server = sf.channel(); sf.sync(); assertEquals(1, latch.getCount()); chan.connect(addr).sync(); assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); assertNull(chan.pipeline().context(WaitUntilActiveHandler.class)); }