List of usage examples for io.netty.channel ChannelFuture channel
Channel channel();
From source file:com.spotify.heroic.rpc.nativerpc.NativeRpcClient.java
License:Apache License
private <R> ChannelFutureListener handleRequestSent(final ResolvableFuture<R> future, final AtomicReference<Timeout> heartbeatTimeout, final Timeout requestTimeout) { return new ChannelFutureListener() { @Override//from w w w.j ava 2 s . c o m public void operationComplete(ChannelFuture f) throws Exception { requestTimeout.cancel(); if (!f.isSuccess()) { future.fail(f.cause()); return; } final Timeout timeout = timer.newTimeout(heartbeatTimeout(f.channel(), future), heartbeatInterval, TimeUnit.MILLISECONDS); heartbeatTimeout.set(timeout); } }; }
From source file:com.spotify.heroic.rpc.nativerpc.NativeRpcProtocolServer.java
License:Apache License
private AsyncFuture<Void> start() { final ServerBootstrap s = new ServerBootstrap(); s.channel(NioServerSocketChannel.class); s.group(bossGroup, workerGroup);//from w ww .j a v a2 s .c om s.childHandler(new NativeRpcServerSession(timer, mapper, container, maxFrameSize, encoding)); final ChannelFuture bind = s.bind(address); bind.addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture f) throws Exception { if (!f.isSuccess()) { bindFuture.fail(f.cause()); return; } serverChannel.set(f.channel()); final InetSocketAddress address = (InetSocketAddress) f.channel().localAddress(); bindFuture.resolve(address); } }); return bindFuture.directTransform(a -> null); }
From source file:com.spotify.netty.handler.codec.zmtp.ZMTPTestConnector.java
License:Apache License
public boolean connectAndReceive(final String ip, final int port, final int serverType) { context = ZMQ.context(1);//from w ww . j a v a 2 s. co m serverSocket = context.socket(serverType); preConnect(serverSocket); serverSocket.bind("tcp://" + ip + ":" + port); EventLoopGroup group = new NioEventLoopGroup(); // Configure the client. final Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { final ZMTPSession session = new ZMTPSession(ZMTPConnectionType.Addressed, "client".getBytes()); ChannelPipeline pl = ch.pipeline(); pl.addLast(new ZMTP10Codec(session)); pl.addLast(new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (onMessage((ZMTPIncomingMessage) msg)) { receivedMessage = true; ctx.channel().close(); } } }); } }); // Start the connection attempt. final ChannelFuture future = bootstrap.connect(new InetSocketAddress(ip, port)); future.awaitUninterruptibly(); afterConnect(serverSocket, future); // Wait until the connection is closed or the connection attempt fails. future.channel().closeFuture().awaitUninterruptibly(); // Shut down thread pools to exit. group.shutdownGracefully(); serverSocket.close(); context.term(); return receivedMessage; }
From source file:com.spotify.netty4.handler.codec.zmtp.ZMTPSocket.java
License:Apache License
/** * Bind this socket to an address./*from w ww . jav a 2 s . c om*/ */ public ListenableFuture<InetSocketAddress> bind(final InetSocketAddress address) { final ServerBootstrap b = new ServerBootstrap().channel(NioServerSocketChannel.class).group(GROUP) .childHandler(new ChannelInitializer()); final ChannelFuture f = b.bind(address); channelGroup.add(f.channel()); if (closed) { f.channel().close(); return immediateFailedFuture(new ClosedChannelException()); } return transform(listenable(f), new Function<Void, InetSocketAddress>() { @Override public InetSocketAddress apply(final Void input) { return (InetSocketAddress) f.channel().localAddress(); } }); }
From source file:com.spotify.netty4.handler.codec.zmtp.ZMTPSocket.java
License:Apache License
/** * Connect this socket to an address./*from w w w. jav a2 s . c o m*/ */ public ListenableFuture<Void> connect(final InetSocketAddress address) { final Bootstrap b = new Bootstrap().group(GROUP).channel(NioSocketChannel.class) .handler(new ChannelInitializer()); final ChannelFuture f = b.connect(address); if (closed) { f.channel().close(); return immediateFailedFuture(new ClosedChannelException()); } return listenable(f); }
From source file:com.srotya.sidewinder.core.ingress.binary.NettyIngestionClient.java
License:Apache License
public static void main(String[] args) throws InterruptedException { EventLoopGroup group = new NioEventLoopGroup(1); try {/*from w w w . j a va2 s .co m*/ Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.SO_RCVBUF, 10485760) .option(ChannelOption.SO_SNDBUF, 10485760).handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new LengthFieldPrepender(4)); p.addLast(new SeriesDataPointEncoder()); } }); // Start the client. ChannelFuture f = b.connect("localhost", 9927).sync(); Channel channel = f.channel(); for (int k = 0; k < TOTAL; k++) { List<DataPoint> data = new ArrayList<>(); for (int i = 0; i < 100; i++) { DataPoint dp = new DataPoint("test", "cpu" + i, "value", Arrays.asList("2"), System.currentTimeMillis() + i * k, System.currentTimeMillis() + i * k); dp.setFp(false); data.add(dp); } // Thread.sleep(1); channel.writeAndFlush(data); } System.out.println("Data points:" + TOTAL); channel.flush(); channel.closeFuture().sync(); System.exit(0); } finally { // Shut down the event loop to terminate all threads. } }
From source file:com.streamsets.pipeline.lib.network.BaseNettyServer.java
License:Apache License
public void start() { Utils.checkNotNull(channelFutures, "Channel future cannot be null"); Utils.checkState(!groups.isEmpty(), "Event group cannot be null"); for (ChannelFuture channelFuture : channelFutures) { channelFuture.channel().closeFuture(); }//from w w w.java2 s . c o m }
From source file:com.streamsets.pipeline.stage.origin.tcp.TestTCPServerSource.java
License:Apache License
@Test public void runTextRecordsWithAck() throws StageException, IOException, ExecutionException, InterruptedException { final String recordSeparatorStr = "\n"; final String[] expectedRecords = TEN_DELIMITED_RECORDS.split(recordSeparatorStr); final int batchSize = expectedRecords.length; final Charset charset = Charsets.ISO_8859_1; final TCPServerSourceConfig configBean = createConfigBean(charset); configBean.dataFormat = DataFormat.TEXT; configBean.tcpMode = TCPMode.DELIMITED_RECORDS; configBean.recordSeparatorStr = recordSeparatorStr; configBean.ports = NetworkUtils.getRandomPorts(1); configBean.recordProcessedAckMessage = "record_ack_${record:id()}"; configBean.batchCompletedAckMessage = "batch_ack_${batchSize}"; configBean.batchSize = batchSize;/*from w w w .jav a 2s . c o m*/ final TCPServerSource source = new TCPServerSource(configBean); final String outputLane = "lane"; final PushSourceRunner runner = new PushSourceRunner.Builder(TCPServerDSource.class, source) .addOutputLane(outputLane).build(); final List<Record> records = new LinkedList<>(); runner.runInit(); EventLoopGroup workerGroup = new NioEventLoopGroup(); ChannelFuture channelFuture = startTcpClient(configBean, workerGroup, TEN_DELIMITED_RECORDS.getBytes(charset), true); runner.runProduce(new HashMap<>(), batchSize, output -> { records.addAll(output.getRecords().get(outputLane)); runner.setStop(); }); runner.waitOnProduce(); // Wait until the connection is closed. final Channel channel = channelFuture.channel(); TCPServerSourceClientHandler clientHandler = channel.pipeline().get(TCPServerSourceClientHandler.class); final List<String> responses = new LinkedList<>(); for (int i = 0; i < batchSize + 1; i++) { // one for each record, plus one for the batch responses.add(clientHandler.getResponse()); } channel.close(); workerGroup.shutdownGracefully(); assertThat(records, hasSize(batchSize)); final List<String> expectedAcks = new LinkedList<>(); for (int i = 0; i < records.size(); i++) { // validate the output record value assertThat(records.get(i).get("/text").getValueAsString(), equalTo(expectedRecords[i])); // validate the record-level ack expectedAcks.add(String.format("record_ack_%s", records.get(i).getHeader().getSourceId())); } // validate the batch-level ack expectedAcks.add(String.format("batch_ack_%d", batchSize)); // because of the vagaries of TCP, we can't be sure that a single ack is returned in each discrete read // this is due to the fact that the server can choose to flush the buffer in different ways, and the client // can choose if/how to buffer on its side when reading from the channel // therefore, we will simply combine all acks in the expected order into a single String and assert at that // level, rather than at an individual read/expected ack level final String combinedAcks = StringUtils.join(responses, ""); assertThat(combinedAcks, startsWith(StringUtils.join(expectedAcks, ""))); }
From source file:com.streamsets.pipeline.stage.origin.tcp.TestTCPServerSource.java
License:Apache License
private void runAndCollectRecords(PushSourceRunner runner, TCPServerSourceConfig configBean, List<Record> records, List<Record> errorRecords, int batchSize, String outputLane, byte[] data, boolean randomlySlice, boolean runEmptyProduceAtEnd) throws StageException, InterruptedException, ExecutionException { runner.runInit();// www . j a va 2 s . c om EventLoopGroup workerGroup = new NioEventLoopGroup(); runner.runProduce(new HashMap<>(), batchSize, output -> { records.addAll(output.getRecords().get(outputLane)); if (!runEmptyProduceAtEnd) { runner.setStop(); } }); ChannelFuture channelFuture = startTcpClient(configBean, workerGroup, data, randomlySlice); // Wait until the connection is closed. channelFuture.channel().closeFuture().sync(); // wait for the push source runner produce to complete runner.waitOnProduce(); errorRecords.addAll(runner.getErrorRecords()); if (runEmptyProduceAtEnd) { runner.runProduce(new HashMap<>(), 0, output -> { runner.setStop(); }); runner.waitOnProduce(); } runner.runDestroy(); workerGroup.shutdownGracefully(); }
From source file:com.streamsets.pipeline.stage.origin.udp.UDPConsumingServer.java
License:Apache License
public void start() { Utils.checkNotNull(channelFutures, "Channel future cannot be null"); Utils.checkNotNull(group, "Event group cannot be null"); for (ChannelFuture channelFuture : channelFutures) { channelFuture.channel().closeFuture(); }/* w w w. j a v a 2 s . c o m*/ }