List of usage examples for io.netty.channel ChannelFuture sync
@Override
ChannelFuture sync() throws InterruptedException;
From source file:com.dwarf.netty.guide.securechat.SecureChatClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); EventLoopGroup group = new NioEventLoopGroup(); try {/*www . jav a2s . co m*/ Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new SecureChatClientInitializer(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 { // The connection is closed automatically on shutdown. group.shutdownGracefully(); } }
From source file:com.elephant.framework.network.telnet.netty.TelnetClient.java
License:Apache License
public void run() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {/* w w w.j av a 2 s . co m*/ Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new TelnetClientInitializer()); // 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:com.flysoloing.learning.network.netty.binary.MemcacheClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {/* w w w . java2 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 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:com.flysoloing.learning.network.netty.redis.RedisClient.java
License:Apache License
public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {/*from w ww. j a v a2s .c om*/ 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(); p.addLast(new RedisDecoder()); p.addLast(new RedisBulkStringAggregator()); p.addLast(new RedisArrayAggregator()); p.addLast(new RedisEncoder()); p.addLast(new RedisClientHandler()); } }); // Start the connection attempt. Channel ch = b.connect(HOST, PORT).sync().channel(); // Read commands from the stdin. System.out.println("Enter Redis commands (quit to end)"); ChannelFuture lastWriteFuture = null; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (;;) { final String input = in.readLine(); final String line = input != null ? input.trim() : null; if (line == null || "quit".equalsIgnoreCase(line)) { // EOF or "quit" ch.close().sync(); break; } else if (line.isEmpty()) { // skip `enter` or `enter` with spaces. continue; } // Sends the received line to the server. lastWriteFuture = ch.writeAndFlush(line); lastWriteFuture.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { System.err.print("write failed: "); future.cause().printStackTrace(System.err); } } }); } // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.sync(); } } finally { group.shutdownGracefully(); } }
From source file:com.flysoloing.learning.network.netty.telnet.TelnetClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {/*from www . j a v a 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)); 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:com.github.milenkovicm.kafka.DataBrokerTest.java
License:Apache License
@Test(expected = KafkaException.class) public void test_sendMessage_unknownTopic() throws Exception { ProducerProperties properties = new ProducerProperties(); properties.override(ProducerProperties.NETTY_DEBUG_PIPELINE, true); DataKafkaBroker dataChannel = new DataKafkaBroker("localhost", START_PORT, 0, "unknown_topic", new NioEventLoopGroup(), properties); dataChannel.connect().sync();//from w w w . j a v a 2s .com final ChannelFuture future = dataChannel.send(freeLaterBuffer("1".getBytes()), 0, freeLaterBuffer(TEST_MESSAGE.getBytes())); future.sync(); dataChannel.disconnect(); }
From source file:com.github.milenkovicm.kafka.DataBrokerTest.java
License:Apache License
@Test public void test_sendMessage_unknownTopicNoAck() throws Exception { ProducerProperties properties = new ProducerProperties(); properties.override(ProducerProperties.NETTY_DEBUG_PIPELINE, true); properties.override(ProducerProperties.DATA_ACK, Acknowledgment.WAIT_FOR_NO_ONE); DataKafkaBroker dataChannel = new DataKafkaBroker("localhost", START_PORT, 0, "unknown_topic", new NioEventLoopGroup(), properties); dataChannel.connect().sync();// ww w .j a va 2s . co m final ChannelFuture future = dataChannel.send(freeLaterBuffer("1".getBytes()), 0, freeLaterBuffer(TEST_MESSAGE.getBytes())); future.sync(); dataChannel.disconnect(); }
From source file:com.github.wolf480pl.ircd.IRCd.java
License:Open Source License
public static void main(String[] args) throws InterruptedException { Logger logger = LoggerFactory.getLogger(IRCd.class); logger.info("Starting IRCd"); ChannelFuture f = new NettyServer(new InetSocketAddress(6667), new IRCSessionHandler()).start(); f.sync(); // Wait for it to bind logger.info("IRCd started"); f.channel().closeFuture().sync(); // Wait for it to close }
From source file:com.google.cloud.pubsub.proxy.moquette.NettyAcceptor.java
License:Open Source License
private void initFactory(String host, int port, final PipelineInitializer pipeliner) { ServerBootstrap bootsrap = new ServerBootstrap(); bootsrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override//from w ww.ja va2 s. c om public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); try { pipeliner.init(pipeline); } catch (Throwable th) { LOG.error("Severe error during pipeline creation", th); throw th; } } }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.SO_REUSEADDR, true) .option(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true); try { // Bind and start to accept incoming connections. ChannelFuture future = bootsrap.bind(host, port); LOG.info("Server binded host: {}, port: {}", host, port); future.sync(); } catch (InterruptedException ex) { LOG.error(null, ex); } }
From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStore.java
License:Open Source License
@SuppressWarnings("FutureReturnValueIgnored") private boolean get(String key, final OutputStream out, boolean casDownload) throws IOException, InterruptedException { final AtomicBoolean dataWritten = new AtomicBoolean(); OutputStream wrappedOut = new OutputStream() { // OutputStream.close() does nothing, which is what we want to ensure that the // OutputStream can't be closed somewhere in the Netty pipeline, so that we can support // retries. The OutputStream is closed in the finally block below. @Override/*from w w w .java 2 s.c o m*/ public void write(byte[] b, int offset, int length) throws IOException { dataWritten.set(true); out.write(b, offset, length); } @Override public void write(int b) throws IOException { dataWritten.set(true); out.write(b); } @Override public void flush() throws IOException { out.flush(); } }; DownloadCommand download = new DownloadCommand(uri, casDownload, key, wrappedOut); Channel ch = null; try { ch = acquireDownloadChannel(); ChannelFuture downloadFuture = ch.writeAndFlush(download); downloadFuture.sync(); return true; } catch (Exception e) { // e can be of type HttpException, because Netty uses Unsafe.throwException to re-throw a // checked exception that hasn't been declared in the method signature. if (e instanceof HttpException) { HttpResponse response = ((HttpException) e).response(); if (!dataWritten.get() && authTokenExpired(response)) { // The error is due to an auth token having expired. Let's try again. refreshCredentials(); return getAfterCredentialRefresh(download); } if (cacheMiss(response.status())) { return false; } } throw e; } finally { if (ch != null) { downloadChannels.release(ch); } } }