List of usage examples for io.netty.channel SimpleChannelInboundHandler SimpleChannelInboundHandler
protected SimpleChannelInboundHandler()
From source file:com.spotify.heroic.rpc.nativerpc.NativeRpcClientSessionInitializer.java
License:Apache License
@Override protected void initChannel(final Channel ch) throws Exception { final ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new ChannelInboundHandlerAdapter() { @Override//from w ww . j a va2 s . c o m public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { bumpTimeout(ctx); ctx.fireChannelRead(msg); } }); // first four bytes are length prefix of message, strip first four bytes. pipeline.addLast(new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4)); pipeline.addLast(new NativeRpcDecoder()); pipeline.addLast(new SimpleChannelInboundHandler<Object>() { @Override protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) throws Exception { if (msg instanceof NativeRpcError) { final NativeRpcError error = (NativeRpcError) msg; if (log.isTraceEnabled()) { log.trace("[{}] remote error: {}", ctx.channel(), error.getMessage()); } future.fail(new NativeRpcRemoteException(address, error.getMessage())); ctx.channel().close(); return; } if (msg instanceof NativeRpcResponse) { if (log.isTraceEnabled()) { log.trace("[{}] response: cancelling heartbeat", ctx.channel()); } final Timeout old = heartbeatTimeout.getAndSet(null); if (old != null) { old.cancel(); } final NativeRpcResponse response = (NativeRpcResponse) msg; final R responseBody = mapper.readValue(response.getBody(), expected); future.resolve(responseBody); return; } if (msg instanceof NativeRpcHeartBeat) { if (log.isTraceEnabled()) { log.trace("[{}] heartbeat: delaying timeout by {}ms", ctx.channel(), heartbeatInterval); } bumpTimeout(ctx); return; } throw new IllegalArgumentException("unable to handle type: " + msg); } }); pipeline.addLast(new SimpleChannelInboundHandler<Object>() { @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { future.fail(cause); } }); pipeline.addLast(new LengthFieldPrepender(4)); pipeline.addLast(new NativeRpcEncoder()); }
From source file:de.ocarthon.core.network.HttpClient.java
License:Apache License
public synchronized String postRequest(String query, List<Map.Entry<String, String>> postParameters, String filePostName, String fileName, ByteBuf fileData, String mime) { if (bootstrap == null) { setupBootstrap();/*from w ww.jav a 2s . c o m*/ } if (channel == null || forceReconnect) { ChannelFuture cf = bootstrap.connect(host, port); forceReconnect = false; cf.awaitUninterruptibly(); channel = cf.channel(); channel.pipeline().addLast("handler", new SimpleChannelInboundHandler<HttpObject>() { @Override protected void messageReceived(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpResponse) { HttpResponse response = ((HttpResponse) msg); String connection = (String) response.headers().get(HttpHeaderNames.CONNECTION); if (connection != null && connection.equalsIgnoreCase(HttpHeaderValues.CLOSE.toString())) forceReconnect = true; } if (msg instanceof HttpContent) { HttpContent chunk = (HttpContent) msg; String message = chunk.content().toString(CharsetUtil.UTF_8); if (!message.isEmpty()) { result[0] = message; synchronized (result) { result.notify(); } } } } }); } boolean isFileAttached = fileData != null && fileData.isReadable(); HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, scheme + "://" + host + ":" + port + "/" + query); HttpPostRequestEncoder bodyReqEncoder; try { bodyReqEncoder = new HttpPostRequestEncoder(httpDataFactory, request, isFileAttached); for (Map.Entry<String, String> entry : postParameters) { bodyReqEncoder.addBodyAttribute(entry.getKey(), entry.getValue()); } if (isFileAttached) { if (mime == null) mime = "application/octet-stream"; MixedFileUpload mfu = new MixedFileUpload(filePostName, fileName, mime, "binary", null, fileData.capacity(), DefaultHttpDataFactory.MINSIZE); mfu.addContent(fileData, true); bodyReqEncoder.addBodyHttpData(mfu); } HttpHeaders headers = request.headers(); headers.set(HttpHeaderNames.HOST, host); headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); headers.set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); headers.set(HttpHeaderNames.USER_AGENT, "OcarthonCore HttpClient"); request = bodyReqEncoder.finalizeRequest(); } catch (Exception e) { throw new NullPointerException("key or value is empty or null"); } channel.write(request); if (bodyReqEncoder.isChunked()) { channel.write(bodyReqEncoder); } channel.flush(); synchronized (result) { try { result.wait(); } catch (InterruptedException e) { return null; } } return result[0]; }
From source file:example.http2.helloworld.server.Http2ServerInitializer.java
License:Apache License
/** * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0 *//* w ww . j a v a 2 s . c om*/ private void configureClearText(SocketChannel ch) { final ChannelPipeline p = ch.pipeline(); final HttpServerCodec sourceCodec = new HttpServerCodec(); final HttpServerUpgradeHandler upgradeHandler = new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory); final CleartextHttp2ServerUpgradeHandler cleartextHttp2ServerUpgradeHandler = new CleartextHttp2ServerUpgradeHandler( sourceCodec, upgradeHandler, new HelloWorldHttp2HandlerBuilder().build()); p.addLast(cleartextHttp2ServerUpgradeHandler); p.addLast(new SimpleChannelInboundHandler<HttpMessage>() { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception { // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP. System.err.println("Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)"); ChannelPipeline pipeline = ctx.pipeline(); ChannelHandlerContext thisCtx = pipeline.context(this); pipeline.addAfter(thisCtx.name(), null, new HelloWorldHttp1Handler("Direct. No Upgrade Attempted.")); pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength)); ctx.fireChannelRead(ReferenceCountUtil.retain(msg)); } }); p.addLast(new UserEventLogger()); }
From source file:hms.webrtc.udp.proxy.remote.RemoteConfiguraitonClient.java
License:Apache License
public static void main(String[] args) { EventLoopGroup group = new NioEventLoopGroup(); try {//from ww w. j ava 2 s .com Bootstrap b = new Bootstrap(); b.group(group).channel(NioDatagramChannel.class) .handler(new SimpleChannelInboundHandler<DatagramPacket>() { @Override protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception { if ("SUCCESS".equals(msg.content().toString(CharsetUtil.UTF_8))) { System.out.println("Sending configuration is success."); } ctx.close(); } }); ch = b.bind(34001).sync().channel(); ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("78737383:40000:40001", CharsetUtil.UTF_8), new InetSocketAddress("127.0.0.1", PORT))).sync(); if (!ch.closeFuture().await(5000)) { Assert.fail("Rtp communication timeout"); } else { } } catch (InterruptedException e) { e.printStackTrace(); } finally { group.shutdownGracefully(); } }
From source file:http2.server.Http2ServerInitializer.java
License:Apache License
/** * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0 *///from w w w. j a v a 2 s . c om private void configureClearText(SocketChannel ch) { final ChannelPipeline p = ch.pipeline(); final HttpServerCodec sourceCodec = new HttpServerCodec(); p.addLast(sourceCodec); p.addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory)); // ? p.addLast(new SimpleChannelInboundHandler<HttpMessage>() { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception { // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP. System.err.println("Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)"); ChannelPipeline pipeline = ctx.pipeline(); ChannelHandlerContext thisCtx = pipeline.context(this); pipeline.addAfter(thisCtx.name(), null, new HelloWorldHttp1Handler("Direct. No Upgrade Attempted.")); pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength)); ctx.fireChannelRead(ReferenceCountUtil.retain(msg)); } }); p.addLast(new UserEventLogger()); }
From source file:hws.channel.net.NetSender.java
License:Apache License
private Channel connectToServer(final String host, final int port) throws Exception { final boolean SSL = false; // Configure SSL.git final SslContext sslCtx; if (SSL) {/*ww w .j av a2 s.c o m*/ sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } else { sslCtx = null; } // Configure the client. //EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(this.group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc(), host, port)); } //p.addLast(new LoggingHandler(LogLevel.INFO)); //p.addLast(new EchoClientHandler()); p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null))); p.addLast(new DefaultEventExecutorGroup(2), new SimpleChannelInboundHandler<Object>() { @Override public void channelActive(ChannelHandlerContext ctx) { //ctx.writeAndFlush(null); } @Override public void channelRead0(ChannelHandlerContext ctx, Object msg) { //future.setReply(msg); //ctx.close(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // Close the connection when an exception is raised. //cause.printStackTrace(); //future.setReply(future.getContext().error(cause.getMessage(), SystemCallErrorType.FATAL)); ctx.close(); } }); } }); // Start the client. ChannelFuture f = b.connect(host, port).sync(); // Wait until the connection is closed. //f.channel().closeFuture().sync(); return f.channel(); //this.channels[id] = f.channel(); //this.groups[id] = group; } finally { // Shut down the event loop to terminate all threads. //group.shutdownGracefully(); //TODO keep group reference so that it can be shutdown afterwards, during the finish } }
From source file:io.advantageous.conekt.dns.impl.DnsClientImpl.java
License:Open Source License
@SuppressWarnings("unchecked") private void lookup(String name, Future result, int... types) { Objects.requireNonNull(name, "no null name accepted"); bootstrap.connect(dnsServer).addListener(new RetryChannelFutureListener(result) { @Override//from w w w . ja v a2s . c om public void onSuccess(ChannelFuture future) throws Exception { DnsQuery query = new DnsQuery(ThreadLocalRandom.current().nextInt()); for (int type : types) { query.addQuestion(new DnsQuestion(name, type)); } future.channel().writeAndFlush(query).addListener(new RetryChannelFutureListener(result) { @Override public void onSuccess(ChannelFuture future) throws Exception { future.channel().pipeline().addLast(new SimpleChannelInboundHandler<DnsResponse>() { @Override protected void channelRead0(ChannelHandlerContext ctx, DnsResponse msg) throws Exception { DnsResponseCode code = DnsResponseCode.valueOf(msg.getHeader().getResponseCode()); if (code == DnsResponseCode.NOERROR) { List<DnsResource> resources = msg.getAnswers(); List<Object> records = new ArrayList<>(resources.size()); for (DnsResource resource : msg.getAnswers()) { Object record = RecordDecoderFactory.getFactory().decode(resource.type(), msg, resource); if (record instanceof InetAddress) { record = ((InetAddress) record).getHostAddress(); } records.add(record); } setResult(result, records); } else { setResult(result, new DnsException(code)); } ctx.close(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { setResult(result, cause); ctx.close(); } }); } }); } }); }
From source file:io.atomix.cluster.messaging.impl.NettyBroadcastService.java
License:Apache License
private CompletableFuture<Void> bootstrapServer() { Bootstrap serverBootstrap = new Bootstrap().group(group) .channelFactory(() -> new NioDatagramChannel(InternetProtocolFamily.IPv4)) .handler(new SimpleChannelInboundHandler<Object>() { @Override/*from w w w . j av a2 s .co m*/ public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { // Nothing will be sent. } }).option(ChannelOption.IP_MULTICAST_IF, iface).option(ChannelOption.SO_REUSEADDR, true); CompletableFuture<Void> future = new CompletableFuture<>(); serverBootstrap.bind(localAddress).addListener((ChannelFutureListener) f -> { if (f.isSuccess()) { serverChannel = f.channel(); future.complete(null); } else { future.completeExceptionally(f.cause()); } }); return future; }
From source file:io.atomix.cluster.messaging.impl.NettyBroadcastService.java
License:Apache License
private CompletableFuture<Void> bootstrapClient() { Bootstrap clientBootstrap = new Bootstrap().group(group) .channelFactory(() -> new NioDatagramChannel(InternetProtocolFamily.IPv4)) .handler(new SimpleChannelInboundHandler<DatagramPacket>() { @Override//w w w .j a va 2 s .c om protected void channelRead0(ChannelHandlerContext context, DatagramPacket packet) throws Exception { byte[] payload = new byte[packet.content().readInt()]; packet.content().readBytes(payload); Message message = SERIALIZER.decode(payload); Set<Consumer<byte[]>> listeners = NettyBroadcastService.this.listeners .get(message.subject()); if (listeners != null) { for (Consumer<byte[]> listener : listeners) { listener.accept(message.payload()); } } } }).option(ChannelOption.IP_MULTICAST_IF, iface).option(ChannelOption.SO_REUSEADDR, true) .localAddress(localAddress.getPort()); CompletableFuture<Void> future = new CompletableFuture<>(); clientBootstrap.bind().addListener((ChannelFutureListener) f -> { if (f.isSuccess()) { clientChannel = (DatagramChannel) f.channel(); log.info("{} joining multicast group {} on port {}", localAddress.getHostName(), groupAddress.getHostName(), groupAddress.getPort()); clientChannel.joinGroup(groupAddress, iface).addListener(f2 -> { if (f2.isSuccess()) { log.info("{} successfully joined multicast group {} on port {}", localAddress.getHostName(), groupAddress.getHostName(), groupAddress.getPort()); future.complete(null); } else { log.info("{} failed to join group {} on port {}", localAddress.getHostName(), groupAddress.getHostName(), groupAddress.getPort()); future.completeExceptionally(f2.cause()); } }); } else { future.completeExceptionally(f.cause()); } }); return future; }
From source file:io.hekate.cluster.seed.multicast.MulticastSeedNodeProvider.java
License:Apache License
private SimpleChannelInboundHandler<DatagramPacket> createSenderHandler(SeedNode thisNode) { return new SimpleChannelInboundHandler<DatagramPacket>() { @Override//w w w . j a v a 2 s.c o m public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception { ByteBuf buf = msg.content(); if (buf.readableBytes() > 4 && buf.readInt() == Utils.MAGIC_BYTES) { MessageTYpe msgType = MessageTYpe.values()[buf.readByte()]; if (msgType == MessageTYpe.SEED_NODE_INFO) { String cluster = decodeUtf(buf); InetSocketAddress address = decodeAddress(buf); SeedNode otherNode = new SeedNode(address, cluster); if (!thisNode.equals(otherNode)) { if (DEBUG) { log.debug("Received seed node info message [node={}]", otherNode); } boolean discovered = false; synchronized (mux) { if (isRegistered()) { if (!seedNodes.contains(otherNode)) { discovered = true; seedNodes.add(otherNode); } } } if (discovered) { log.info("Seed node discovered [address={}]", otherNode.address()); } } } } } }; }