List of usage examples for io.netty.channel SimpleChannelInboundHandler SimpleChannelInboundHandler
protected SimpleChannelInboundHandler()
From source file:org.apache.hadoop.hbase.util.FanOutOneBlockAsyncDFSOutputHelper.java
License:Apache License
private static void processWriteBlockResponse(Channel channel, final DatanodeInfo dnInfo, final Promise<Channel> promise, final int timeoutMs) { channel.pipeline().addLast(new IdleStateHandler(timeoutMs, 0, 0, TimeUnit.MILLISECONDS), new ProtobufVarint32FrameDecoder(), new ProtobufDecoder(BlockOpResponseProto.getDefaultInstance()), new SimpleChannelInboundHandler<BlockOpResponseProto>() { @Override/*from ww w . j a va 2 s.c o m*/ protected void channelRead0(ChannelHandlerContext ctx, BlockOpResponseProto resp) throws Exception { Status pipelineStatus = resp.getStatus(); if (PipelineAck.isRestartOOBStatus(pipelineStatus)) { throw new IOException("datanode " + dnInfo + " is restarting"); } String logInfo = "ack with firstBadLink as " + resp.getFirstBadLink(); if (resp.getStatus() != Status.SUCCESS) { if (resp.getStatus() == Status.ERROR_ACCESS_TOKEN) { throw new InvalidBlockTokenException("Got access token error" + ", status message " + resp.getMessage() + ", " + logInfo); } else { throw new IOException("Got error" + ", status=" + resp.getStatus().name() + ", status message " + resp.getMessage() + ", " + logInfo); } } // success ChannelPipeline p = ctx.pipeline(); while (p.first() != null) { p.removeFirst(); } // Disable auto read here. Enable it after we setup the streaming pipeline in // FanOutOneBLockAsyncDFSOutput. ctx.channel().config().setAutoRead(false); promise.trySuccess(ctx.channel()); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { promise.tryFailure(new IOException("connection to " + dnInfo + " is closed")); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent && ((IdleStateEvent) evt).state() == IdleState.READER_IDLE) { promise.tryFailure( new IOException("Timeout(" + timeoutMs + "ms) waiting for response")); } else { super.userEventTriggered(ctx, evt); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { promise.tryFailure(cause); } }); }
From source file:org.codice.alliance.distribution.sdk.video.stream.mpegts.MpegTsUdpClient.java
License:Open Source License
public static void broadcastVideo(String videoFilePath, String ip, int port, long tsDurationMillis, int minDatagramSize, int maxDatagramSize, boolean fractionalTs, String networkInterfaceName) { Optional<InetAddress> inetAddressOptional = findLocalAddress(networkInterfaceName); EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); try {// w w w . ja v a 2 s .c om Bootstrap bootstrap = new Bootstrap(); bootstrap.group(eventLoopGroup).channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(new SimpleChannelInboundHandler<DatagramPacket>() { @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket) throws Exception { LOGGER.trace("Reading datagram from channel"); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { LOGGER.error("Exception occurred while handling datagram packet.", cause); ctx.close(); } }); Channel ch; if (inetAddressOptional.isPresent()) { ch = bootstrap.bind(inetAddressOptional.get(), 0).sync().channel(); } else { ch = bootstrap.bind(0).sync().channel(); } File videoFile = new File(videoFilePath); long bytesSent = 0; long tsPacketCount = videoFile.length() / PACKET_SIZE; double delayPerPacket = tsDurationMillis / (double) tsPacketCount; long startTime = System.currentTimeMillis(); Random rand = new Random(0); long nextPacketLog = PACKET_LOG_PERIOD; long nextByteLog = BYTE_LOG_PERIOD; try (final InputStream fis = new BufferedInputStream(new FileInputStream(videoFile))) { byte[] buffer = new byte[DISK_IO_BUFFER_SIZE]; int datagramSize = getPacketSize(rand, minDatagramSize, maxDatagramSize, fractionalTs); byte[] dgramBuffer = new byte[datagramSize]; int writeStart = 0; int writeEnd = datagramSize; int readEnd; while ((readEnd = fis.read(buffer)) != -1) { int readStart = 0; while (readStart < readEnd) { int bytesToCopy = Math.min(writeEnd - writeStart, readEnd - readStart); System.arraycopy(buffer, readStart, dgramBuffer, writeStart, bytesToCopy); readStart += bytesToCopy; writeStart += bytesToCopy; if (writeStart == writeEnd) { transmit(ch, dgramBuffer, ip, port); bytesSent += dgramBuffer.length; long packetsSent = bytesSent / PACKET_SIZE; long currentTime = System.currentTimeMillis(); long elapsedTime = currentTime - startTime; double predictedTime = packetsSent * delayPerPacket; if ((predictedTime - elapsedTime) >= 50) { Thread.sleep((long) predictedTime - elapsedTime); } if (packetsSent >= nextPacketLog) { LOGGER.debug("Packets sent: {}, Bytes sent: {}", packetsSent, bytesSent); nextPacketLog += PACKET_LOG_PERIOD; } if (bytesSent >= nextByteLog) { LOGGER.debug("Packets sent: {}, Bytes sent: {}", packetsSent, bytesSent); nextByteLog += BYTE_LOG_PERIOD; } datagramSize = getPacketSize(rand, minDatagramSize, maxDatagramSize, fractionalTs); dgramBuffer = new byte[datagramSize]; writeStart = 0; writeEnd = datagramSize; } } } if (writeStart > 0) { byte[] tmp = new byte[writeStart]; System.arraycopy(dgramBuffer, 0, tmp, 0, tmp.length); transmit(ch, tmp, ip, port); } } long endTime = System.currentTimeMillis(); LOGGER.trace("Time Elapsed: {}", endTime - startTime); LOGGER.trace("Elapsed Time minus predicted time: {}", (endTime - startTime) - tsDurationMillis); if (!ch.closeFuture().await(100)) { LOGGER.error("Channel timeout"); } LOGGER.trace("Bytes sent: {} ", bytesSent); } catch (InterruptedException | IOException e) { LOGGER.error("Unable to generate stream.", e); } finally { // Shut down the event loop to terminate all threads. eventLoopGroup.shutdownGracefully(); } }
From source file:org.glassfish.jersey.netty.httpserver.JerseyServerInitializer.java
License:Open Source License
/** * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2. *//*from w w w.j av a2s . c o m*/ private void configureClearText(SocketChannel ch) { final ChannelPipeline p = ch.pipeline(); final HttpServerCodec sourceCodec = new HttpServerCodec(); p.addLast(sourceCodec); p.addLast(new HttpServerUpgradeHandler(sourceCodec, new HttpServerUpgradeHandler.UpgradeCodecFactory() { @Override public HttpServerUpgradeHandler.UpgradeCodec newUpgradeCodec(CharSequence protocol) { if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) { return new Http2ServerUpgradeCodec( new Http2Codec(true, new JerseyHttp2ServerHandler(baseUri, container))); } else { return null; } } })); 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. // "Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)"); ChannelPipeline pipeline = ctx.pipeline(); ChannelHandlerContext thisCtx = pipeline.context(this); pipeline.addAfter(thisCtx.name(), null, new JerseyServerHandler(baseUri, container)); pipeline.replace(this, null, new ChunkedWriteHandler()); ctx.fireChannelRead(msg); } }); }
From source file:org.graylog2.gelfclient.transport.GelfTcpTransport.java
License:Apache License
@Override protected void createBootstrap(final EventLoopGroup workerGroup) { final Bootstrap bootstrap = new Bootstrap(); final GelfSenderThread senderThread = new GelfSenderThread(queue); bootstrap.group(workerGroup).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout()) .option(ChannelOption.TCP_NODELAY, config.isTcpNoDelay()) .option(ChannelOption.SO_KEEPALIVE, config.isTcpKeepAlive()) .remoteAddress(config.getRemoteAddress()).handler(new ChannelInitializer<SocketChannel>() { @Override/*from ww w .j a v a 2 s. c o m*/ protected void initChannel(SocketChannel ch) throws Exception { if (config.isTlsEnabled()) { LOG.debug("TLS enabled."); final SslContext sslContext; if (!config.isTlsCertVerificationEnabled()) { // If the cert should not be verified just use an insecure trust manager. LOG.debug("TLS certificate verification disabled!"); sslContext = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } else if (config.getTlsTrustCertChainFile() != null) { // If a cert chain file is set, use it. LOG.debug("TLS certificate chain file: {}", config.getTlsTrustCertChainFile()); sslContext = SslContext.newClientContext(config.getTlsTrustCertChainFile()); } else { // Otherwise use the JVM default cert chain. sslContext = SslContext.newClientContext(); } ch.pipeline().addLast(sslContext.newHandler(ch.alloc())); } // We cannot use GZIP encoding for TCP because the headers contain '\0'-bytes then. // The graylog2-server uses '\0'-bytes as delimiter for TCP frames. ch.pipeline().addLast(new GelfMessageJsonEncoder()); ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() { @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { // We do not receive data. } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { senderThread.start(ctx.channel()); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { LOG.info("Channel disconnected!"); senderThread.stop(); scheduleReconnect(ctx.channel().eventLoop()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { LOG.error("Exception caught", cause); } }); } }); if (config.getSendBufferSize() != -1) { bootstrap.option(ChannelOption.SO_SNDBUF, config.getSendBufferSize()); } bootstrap.connect().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { LOG.debug("Connected!"); } else { LOG.error("Connection failed: {}", future.cause().getMessage()); scheduleReconnect(future.channel().eventLoop()); } } }); }
From source file:org.graylog2.gelfclient.transport.GelfUdpTransport.java
License:Apache License
@Override protected void createBootstrap(final EventLoopGroup workerGroup) { final Bootstrap bootstrap = new Bootstrap(); final GelfSenderThread senderThread = new GelfSenderThread(queue); bootstrap.group(workerGroup).channel(NioDatagramChannel.class).handler(new ChannelInitializer<Channel>() { @Override//www . jav a 2 s. c o m protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new GelfMessageUdpEncoder(config.getRemoteAddress())); ch.pipeline().addLast(new GelfMessageChunkEncoder()); ch.pipeline().addLast(new GelfCompressionEncoder()); ch.pipeline().addLast(new GelfMessageJsonEncoder()); ch.pipeline().addLast(new SimpleChannelInboundHandler<DatagramPacket>() { @Override protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception { // We do not receive data. } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { senderThread.start(ctx.channel()); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { senderThread.stop(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { LOG.error("Exception caught", cause); } }); } }); if (config.getSendBufferSize() != -1) { bootstrap.option(ChannelOption.SO_SNDBUF, config.getSendBufferSize()); } bootstrap.bind(0); }
From source file:org.hornetq.tests.integration.transports.netty.NettyConnectorWithHTTPUpgradeTest.java
License:Apache License
private void startWebServer(int port) throws InterruptedException { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override/*from w w w .j ava 2 s . co m*/ protected void initChannel(SocketChannel ch) throws Exception { // create a HTTP server ChannelPipeline p = ch.pipeline(); p.addLast("decoder", new HttpRequestDecoder()); p.addLast("encoder", new HttpResponseEncoder()); p.addLast("http-upgrade-handler", new SimpleChannelInboundHandler<Object>() { // handle HTTP GET + Upgrade with a handshake specific to HornetQ remoting. @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; for (Map.Entry<String, String> entry : request.headers()) { System.out.println(entry); } String upgrade = request.headers().get(UPGRADE); String secretKey = request.headers().get(SEC_HORNETQ_REMOTING_KEY); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, SWITCHING_PROTOCOLS); response.headers().set(UPGRADE, upgrade); response.headers().set(SEC_HORNETQ_REMOTING_ACCEPT, createExpectedResponse(MAGIC_NUMBER, secretKey)); ctx.writeAndFlush(response); // when the handshake is successful, the HTTP handlers are removed ctx.pipeline().remove("decoder"); ctx.pipeline().remove("encoder"); ctx.pipeline().remove(this); System.out.println("HTTP handshake sent, transferring channel"); // transfer the control of the channel to the Netty Acceptor NettyAcceptor acceptor = (NettyAcceptor) server.getRemotingService() .getAcceptor(acceptorName); acceptor.transfer(ctx.channel()); // at this point, the HTTP upgrade process is over and the netty acceptor behaves like regular ones. } } }); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } }); b.bind(port).sync(); }
From source file:org.ogcs.okra.example.benchmark.BenchmarkClient.java
License:Apache License
@Override protected ChannelHandler newChannelInitializer() { return new ChannelInitializer<NioSocketChannel>() { @Override//from w w w.j av a2s .c o m protected void initChannel(NioSocketChannel ch) throws Exception { ChannelPipeline cp = ch.pipeline(); cp.addLast("frame", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 2, 0, 2)); cp.addLast("prepender", FRAME_PREPENDER); // Any other useful handler cp.addLast("strDecoder", STRING_DECODER); cp.addLast("strEncoder", STRING_ENCODER); cp.addLast("handler", new SimpleChannelInboundHandler<String>() { @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { COUNT.getAndIncrement(); // ChannelPromise voidPromise = ctx.voidPromise(); // if (ctx.channel().isWritable()) { // ctx.writeAndFlush(msg, voidPromise); // } else { // ctx.channel().eventLoop().schedule(() -> { // ctx.writeAndFlush(msg, voidPromise); // }, 1L, TimeUnit.SECONDS); // } } }); } }; }
From source file:org.ogcs.okra.example.Client.java
License:Apache License
public static void main(String[] args) { TcpProtocolClient client = new TcpProtocolClient("127.0.0.1", 9008) { @Override/*from ww w .ja va2 s . c o m*/ protected ChannelHandler newChannelInitializer() { return new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline cp = ch.pipeline(); cp.addLast("frame", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 2, 0, 2)); cp.addLast("prepender", FRAME_PREPENDER); cp.addLast("decoder", GPB_DECODER_HANDLER); cp.addLast("encoder", GPB_ENCODER_HANDLER); // handler cp.addLast("handler", new SimpleChannelInboundHandler<Response>() { @Override protected void channelRead0(ChannelHandlerContext ctx, Response msg) throws Exception { System.out.println("msg:" + msg.getId() + ", "); } }); // cp.addLast("handler", new ServerHandler()); } }; } }; client.start(); AtomicInteger ID = new AtomicInteger(0); Channel client1 = client.client(); client1.writeAndFlush(Request.newBuilder().setId(ID.incrementAndGet()).setApi(1).build()); }
From source file:org.ogcs.okra.example.game.impl.arpg.ArpgLogicServer.java
License:Apache License
@Override protected ChannelHandler newChannelInitializer() { return new ChannelInitializer<NioSocketChannel>() { @Override//from ww w . j a v a 2 s . c o m protected void initChannel(NioSocketChannel ch) throws Exception { ChannelPipeline cp = ch.pipeline(); cp.addLast("frame", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 2, 0, 2)); cp.addLast("prepender", FRAME_PREPENDER); cp.addLast("decoder", STRING_DECODER); cp.addLast("encoder", STRING_ENCODER); cp.addLast("handler", new SimpleChannelInboundHandler<String>() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); sets.add(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); sets.remove(ctx); } @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { // JSONObject jsonObject = JSON.parseObject(msg); System.out.println(msg); for (ChannelHandlerContext set : sets) { set.writeAndFlush(msg); } } }); } }; }
From source file:org.openremote.agent.protocol.io.AbstractIoServer.java
License:Open Source License
/** * Initialise the specified client channel (will be called when a new client connection is made) *//*from w w w .ja v a 2 s . c om*/ protected void initClientChannel(U channel) { LOG.fine("Client initialising: " + getClientDescriptor(channel)); // Add handler to track when a channel becomes active and to handle exceptions channel.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { onClientConnected(channel); super.channelActive(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { onClientDisconnected(channel); super.channelInactive(ctx); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { onDecodeException(ctx, cause); super.exceptionCaught(ctx, cause); } }); channel.pipeline().addLast(new ChannelOutboundHandlerAdapter() { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { onEncodeException(ctx, cause); super.exceptionCaught(ctx, cause); } }); addDecoders(channel); addEncoders(channel); // Add handler to route the final messages channel.pipeline().addLast(new SimpleChannelInboundHandler<T>() { @Override protected void channelRead0(ChannelHandlerContext ctx, T msg) { onMessageReceived(channel, msg); } }); }