List of usage examples for io.netty.channel Channel pipeline
ChannelPipeline pipeline();
From source file:WorldClockClient.java
License:Apache License
public void run() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {/* ww w . j a v a 2 s . co 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:alluxio.client.netty.NettyRPC.java
License:Apache License
/** * Sends a request and waits for a response. * * @param context the netty RPC context//from w w w . j a v a 2s . c om * @param request the RPC request * @return the RPC response */ public static ProtoMessage call(final NettyRPCContext context, ProtoMessage request) throws IOException { Channel channel = Preconditions.checkNotNull(context.getChannel()); Promise<ProtoMessage> promise = channel.eventLoop().newPromise(); channel.pipeline().addLast(new RPCHandler(promise)); channel.writeAndFlush(new RPCProtoMessage(request)); ProtoMessage message; try { message = promise.get(context.getTimeoutMs(), TimeUnit.MILLISECONDS); } catch (ExecutionException | TimeoutException e) { throw new IOException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { if (channel.isOpen()) { channel.pipeline().removeLast(); } } if (message.isResponse()) { CommonUtils.unwrapResponse(message.asResponse()); } return message; }
From source file:alluxio.client.netty.NettyUnderFileSystemBlockReader.java
License:Apache License
@Override public ByteBuffer read(InetSocketAddress address, long blockId, long offset, long length, long sessionId, boolean noCache) throws IOException { Channel channel = null; ClientHandler clientHandler = null;/*from w w w . j av a 2 s .c o m*/ Metrics.NETTY_UFS_BLOCK_READ_OPS.inc(); try { channel = mContext.acquireNettyChannel(address); if (!(channel.pipeline().last() instanceof ClientHandler)) { channel.pipeline().addLast(new ClientHandler()); } clientHandler = (ClientHandler) channel.pipeline().last(); SingleResponseListener listener = new SingleResponseListener(); clientHandler.addListener(listener); ChannelFuture channelFuture = channel.writeAndFlush( new RPCUnderFileSystemBlockReadRequest(blockId, offset, length, sessionId, noCache)); channelFuture = channelFuture.sync(); if (channelFuture.isDone() && !channelFuture.isSuccess()) { LOG.error("Failed to read from %s for block %d with error %s.", address.toString(), blockId, channelFuture.cause()); throw new IOException(channelFuture.cause()); } RPCResponse response = listener.get(NettyClient.TIMEOUT_MS, TimeUnit.MILLISECONDS); switch (response.getType()) { case RPC_BLOCK_READ_RESPONSE: RPCBlockReadResponse blockResponse = (RPCBlockReadResponse) response; LOG.debug("Data {} from machine {} received", blockId, address); RPCResponse.Status status = blockResponse.getStatus(); if (status == RPCResponse.Status.SUCCESS) { // always clear the previous response before reading another one close(); mReadResponse = blockResponse; return blockResponse.getPayloadDataBuffer().getReadOnlyByteBuffer(); } throw new IOException(status.getMessage() + " response: " + blockResponse); case RPC_ERROR_RESPONSE: RPCErrorResponse error = (RPCErrorResponse) response; throw new IOException(error.getStatus().getMessage()); default: throw new IOException(ExceptionMessage.UNEXPECTED_RPC_RESPONSE.getMessage(response.getType(), RPCMessage.Type.RPC_BLOCK_READ_RESPONSE)); } } catch (Exception e) { Metrics.NETTY_UFS_BLOCK_READ_FAILURES.inc(); try { if (channel != null) { channel.close().sync(); } } catch (InterruptedException ee) { throw new RuntimeException(ee); } throw new IOException(e); } finally { if (clientHandler != null) { clientHandler.removeListeners(); } if (channel != null) { mContext.releaseNettyChannel(address, channel); } } }
From source file:alluxio.network.netty.NettyClient.java
License:Apache License
/** * Creates and returns a new Netty client bootstrap for clients to connect to remote servers. * * @param address the socket address/*from www. j a v a 2 s. c o m*/ * @return the new client {@link Bootstrap} */ public static Bootstrap createClientBootstrap(SocketAddress address) { final Bootstrap boot = new Bootstrap(); boot.group(WORKER_GROUP).channel( NettyUtils.getClientChannelClass(NettyUtils.CHANNEL_TYPE, !(address instanceof InetSocketAddress))); boot.option(ChannelOption.SO_KEEPALIVE, true); boot.option(ChannelOption.TCP_NODELAY, true); boot.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); if (NettyUtils.CHANNEL_TYPE == ChannelType.EPOLL) { boot.option(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED); } // After 10 missed heartbeat attempts and no write activity, the server will close the channel. final long timeoutMs = Configuration.getMs(PropertyKey.NETWORK_NETTY_HEARTBEAT_TIMEOUT_MS); final long heartbeatPeriodMs = Math.max(timeoutMs / 10, 1); boot.handler(new ChannelInitializer<Channel>() { @Override public void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(RPCMessage.createFrameDecoder()); pipeline.addLast(ENCODER); pipeline.addLast(DECODER); pipeline.addLast(new IdleStateHandler(0, heartbeatPeriodMs, 0, TimeUnit.MILLISECONDS)); pipeline.addLast(new IdleWriteHandler()); } }); return boot; }
From source file:alluxio.network.netty.NettyRPC.java
License:Apache License
/** * Sends a request and waits for a response. * * @param context the netty RPC context//from ww w . java 2 s. c o m * @param request the RPC request * @return the RPC response */ public static ProtoMessage call(final NettyRPCContext context, ProtoMessage request) throws IOException { Channel channel = Preconditions.checkNotNull(context.getChannel()); final Promise<ProtoMessage> promise = channel.eventLoop().newPromise(); channel.pipeline().addLast(new RPCHandler(promise)); channel.writeAndFlush(new RPCProtoMessage(request)).addListener((ChannelFuture future) -> { if (future.cause() != null) { future.channel().close(); promise.tryFailure(future.cause()); } }); ProtoMessage message; try { message = promise.get(context.getTimeoutMs(), TimeUnit.MILLISECONDS); } catch (ExecutionException | TimeoutException e) { CommonUtils.closeChannel(channel); throw new IOException(e); } catch (InterruptedException e) { CommonUtils.closeChannel(channel); throw new RuntimeException(e); } finally { if (channel.isOpen()) { channel.pipeline().removeLast(); } } if (message.isResponse()) { CommonUtils.unwrapResponseFrom(message.asResponse(), context.getChannel()); } return message; }
From source file:at.yawk.dbus.protocol.DbusConnector.java
/** * Connect to the dbus server at the given {@link SocketAddress}. *//*from w w w. j ava 2 s . com*/ public DbusChannel connect(SocketAddress address) throws Exception { Bootstrap localBootstrap = bootstrap.clone(); if (address instanceof DomainSocketAddress) { localBootstrap.group(new EpollEventLoopGroup()); localBootstrap.channel(EpollDomainSocketChannel.class); } else { localBootstrap.group(new NioEventLoopGroup()); localBootstrap.channel(NioSocketChannel.class); } Channel channel = localBootstrap.connect(address).sync().channel(); AuthClient authClient = new AuthClient(); if (LoggingInboundAdapter.isEnabled()) { channel.pipeline().addLast(new LoggingInboundAdapter()); } channel.pipeline().addLast("auth", authClient); channel.config().setAutoRead(true); log.trace("Pipeline is now {}", channel.pipeline()); // I really don't get why dbus does this channel.write(Unpooled.wrappedBuffer(new byte[] { 0 })); if (authMechanism == null) { authMechanism = new ExternalAuthMechanism(); } CompletionStage<?> completionPromise = authClient.startAuth(channel, authMechanism); SwappableMessageConsumer swappableConsumer = new SwappableMessageConsumer(initialConsumer); completionPromise.toCompletableFuture().thenRun(() -> { channel.pipeline().replace("auth", "main", new DbusMainProtocol(swappableConsumer)); log.trace("Pipeline is now {}", channel.pipeline()); }).get(); DbusChannelImpl dbusChannel = new DbusChannelImpl(channel, swappableConsumer); dbusChannel.write(MessageFactory.methodCall("/", "org.freedesktop.DBus", "org.freedesktop.DBus", "Hello")); return dbusChannel; }
From source file:at.yawk.dbus.protocol.DbusConnectorTest.java
@Test(enabled = false) public void testServer() throws Exception { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.channel(EpollServerDomainSocketChannel.class); bootstrap.group(new EpollEventLoopGroup()); bootstrap.childHandler(new ChannelInitializer<Channel>() { @Override/*from www .java 2s. c om*/ protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new CommandCodec()).addLast(new ChannelDuplexHandler() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof NegotiateUnixFd) { ch.writeAndFlush(new Error("error")); } if (msg instanceof Begin) { ch.pipeline().addLast(new LoggingInboundAdapter()) .addLast(new DbusMainProtocol(new MessageConsumer() { @Override public boolean requireAccept(MessageHeader header) { return true; } @Override public void accept(DbusMessage message) { DbusMessage response = new DbusMessage(); MessageHeader header = new MessageHeader(); header.setMessageType(MessageType.ERROR); header.addHeader(HeaderField.REPLY_SERIAL, BasicObject.createUint32(message.getHeader().getSerial())); //header.addHeader(HeaderField.SIGNATURE, SignatureObject.create( // Collections.singletonList(BasicType.VARIANT))); header.addHeader(HeaderField.ERROR_NAME, BasicObject.createString("Error")); response.setHeader(header); MessageBody body = new MessageBody(); //body.add(VariantObject.create(BasicObject.createString("testing!"))); response.setBody(body); ch.writeAndFlush(response); } })); ch.pipeline().remove((Class) getClass()); ch.pipeline().remove(CommandCodec.class); } } }); ch.writeAndFlush(new Ok(UUID.randomUUID())); } }); bootstrap.bind(new DomainSocketAddress(new File("test"))); try { DbusUtil.callCommand(("dbus-send --address=unix:path=" + new File(".").getAbsolutePath() + "/test --dest=org.freedesktop.UPower --print-reply " + "/org/freedesktop/UPower/devices/DisplayDevice org.freedesktop.DBus.Properties.Get string:org" + ".freedesktop.UPower.Device string:State").split(" ")); } catch (Exception e) { e.printStackTrace(); } TimeUnit.DAYS.sleep(1); }
From source file:c5db.client.C5NettyConnectionManager.java
License:Apache License
private boolean isHandShakeConnected(Channel channel) { final ChannelPipeline pipeline = channel.pipeline(); final WebsocketProtostuffEncoder encoder = pipeline.get(WebsocketProtostuffEncoder.class); return encoder.getHandShaker().isHandshakeComplete(); }
From source file:cc.agentx.client.net.nio.XConnectHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception { boolean proxyMode = isAgentXNeeded(request.host()); log.info("\tClient -> Proxy \tTarget {}:{} [{}]", request.host(), request.port(), proxyMode ? "AGENTX" : "DIRECT"); Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { @Override//w w w. ja v a2 s . co m public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType())) .addListener(channelFuture -> { ByteBuf byteBuf = Unpooled.buffer(); request.encodeAsByteBuf(byteBuf); if (byteBuf.hasArray()) { byte[] xRequestBytes = new byte[byteBuf.readableBytes()]; byteBuf.getBytes(0, xRequestBytes); if (proxyMode) { // handshaking to remote proxy xRequestBytes = requestWrapper.wrap(xRequestBytes); outboundChannel.writeAndFlush(Unpooled.wrappedBuffer( exposeRequest ? xRequestBytes : wrapper.wrap(xRequestBytes))); } // task handover ReferenceCountUtil.retain(request); // auto-release? a trap? ctx.pipeline().remove(XConnectHandler.this); outboundChannel.pipeline().addLast(new XRelayHandler(ctx.channel(), proxyMode ? wrapper : rawWrapper, false)); ctx.pipeline().addLast(new XRelayHandler(outboundChannel, proxyMode ? wrapper : rawWrapper, true)); } }); } else { ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); if (ctx.channel().isActive()) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }); String host = request.host(); int port = request.port(); if (host.equals(config.getConsoleDomain())) { host = "localhost"; port = config.getConsolePort(); } else if (proxyMode) { host = config.getServerHost(); port = config.getServerPort(); } // ping target bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { ctx.channel().writeAndFlush( new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); if (ctx.channel().isActive()) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }); }
From source file:cc.agentx.server.net.nio.XConnectHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { try {/* ww w . j a va2 s .c om*/ ByteBuf byteBuf = (ByteBuf) msg; if (!byteBuf.hasArray()) { byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.getBytes(0, bytes); if (!requestParsed) { if (!exposedRequest) { bytes = wrapper.unwrap(bytes); if (bytes == null) { log.info("\tClient -> Proxy \tHalf Request"); return; } } XRequest xRequest = requestWrapper.parse(bytes); String host = xRequest.getHost(); int port = xRequest.getPort(); int dataLength = xRequest.getSubsequentDataLength(); if (dataLength > 0) { byte[] tailData = Arrays.copyOfRange(bytes, bytes.length - dataLength, bytes.length); if (exposedRequest) { tailData = wrapper.unwrap(tailData); if (tailData != null) { tailDataBuffer.write(tailData, 0, tailData.length); } } else { tailDataBuffer.write(tailData, 0, tailData.length); } } log.info("\tClient -> Proxy \tTarget {}:{}{}", host, port, DnsCache.isCached(host) ? " [Cached]" : ""); if (xRequest.getAtyp() == XRequest.Type.DOMAIN) { try { host = DnsCache.get(host); if (host == null) { host = xRequest.getHost(); } } catch (UnknownHostException e) { log.warn("\tClient <- Proxy \tBad DNS! ({})", e.getMessage()); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); return; } } Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { @Override public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { // handle tail byte[] tailData = tailDataBuffer.toByteArray(); tailDataBuffer.close(); if (tailData.length > 0) { log.info("\tClient ==========> Target \tSend Tail [{} bytes]", tailData.length); } outboundChannel .writeAndFlush((tailData.length > 0) ? Unpooled.wrappedBuffer(tailData) : Unpooled.EMPTY_BUFFER) .addListener(channelFuture -> { // task handover outboundChannel.pipeline() .addLast(new XRelayHandler(ctx.channel(), wrapper, false)); ctx.pipeline() .addLast(new XRelayHandler(outboundChannel, wrapper, true)); ctx.pipeline().remove(XConnectHandler.this); }); } else { if (ctx.channel().isActive()) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } } }); final String finalHost = host; bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.SO_KEEPALIVE, true) .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { if (ctx.channel().isActive()) { log.warn("\tClient <- Proxy \tBad Ping! ({}:{})", finalHost, port); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } } }); requestParsed = true; } else { bytes = wrapper.unwrap(bytes); if (bytes != null) tailDataBuffer.write(bytes, 0, bytes.length); } } } finally { ReferenceCountUtil.release(msg); } }