Package io.netty.channel

Examples of io.netty.channel.Channel


        int increment = settings.objectSizeEstimator.estimateSize(task);

        if (task instanceof ChannelEventRunnable) {
            ChannelEventRunnable eventTask = (ChannelEventRunnable) task;
            eventTask.estimatedSize = increment;
            Channel channel = eventTask.getEvent().getChannel();
            long channelCounter = getChannelCounter(channel).addAndGet(increment);
            //System.out.println("IC: " + channelCounter + ", " + increment);
            if (maxChannelMemorySize != 0 && channelCounter >= maxChannelMemorySize && channel.isOpen()) {
                if (channel.isReadable()) {
                    //System.out.println("UNREADABLE");
                    ChannelHandlerContext ctx = eventTask.getContext();
                    if (ctx.getHandler() instanceof ExecutionHandler) {
                        // readSuspended = true;
                        ctx.setAttachment(Boolean.TRUE);
                    }
                    channel.setReadable(false);
                }
            }
        } else {
            ((MemoryAwareRunnable) task).estimatedSize = increment;
        }
View Full Code Here


            totalLimiter.decrease(increment);
        }

        if (task instanceof ChannelEventRunnable) {
            ChannelEventRunnable eventTask = (ChannelEventRunnable) task;
            Channel channel = eventTask.getEvent().getChannel();
            long channelCounter = getChannelCounter(channel).addAndGet(-increment);
            //System.out.println("DC: " + channelCounter + ", " + increment);
            if (maxChannelMemorySize != 0 && channelCounter < maxChannelMemorySize && channel.isOpen()) {
                if (!channel.isReadable()) {
                    //System.out.println("READABLE");
                    ChannelHandlerContext ctx = eventTask.getContext();
                    if (ctx.getHandler() instanceof ExecutionHandler) {
                        // readSuspended = false;
                        ctx.setAttachment(null);
                    }
                    channel.setReadable(true);
                }
            }
        }
    }
View Full Code Here

                // compute the number of ms to wait before reopening the channel
                long wait = getTimeToWait(readLimit, trafficCounter
                        .getCurrentReadBytes(), trafficCounter.getLastTime(),
                        curtime);
                if (wait > MINIMAL_WAIT) { // At least 10ms seems a minimal time in order to
                    Channel channel = arg0.getChannel();
                    // try to limit the traffic
                    if (channel != null && channel.isConnected()) {
                        // Channel version
                        if (executor == null) {
                            // Sleep since no executor
                            //logger.info("Read sleep since no executor for "+wait+" ms for "+this);
                            if (release.get()) {
                                return;
                            }
                            Thread.sleep(wait);
                            return;
                        }
                        if (arg0.getAttachment() == null) {
                            // readSuspended = true;
                            arg0.setAttachment(Boolean.TRUE);
                            channel.setReadable(false);
                            //logger.info("Read will wakeup after "+wait+" ms "+this);
                            executor.execute(new ReopenRead(arg0, wait));
                        } else {
                            // should be waiting: but can occurs sometime so as a FIX
                            //logger.info("Read sleep ok but should not be here: "+wait+" "+this);
View Full Code Here

        if (handshaken && !isEnableRenegotiation()) {
            throw new IllegalStateException("renegotiation disabled");
        }

        ChannelHandlerContext ctx = this.ctx;
        Channel channel = ctx.getChannel();
        ChannelFuture handshakeFuture;
        Exception exception = null;

        synchronized (handshakeLock) {
            if (handshaking) {
View Full Code Here

     * Sends an SSL {@code close_notify} message to the specified channel and
     * destroys the underlying {@link SSLEngine}.
     */
    public ChannelFuture close() {
        ChannelHandlerContext ctx = this.ctx;
        Channel channel = ctx.getChannel();
        try {
            engine.closeOutbound();
            return wrapNonAppData(ctx, channel);
        } catch (SSLException e) {
            fireExceptionCaught(ctx, e);
View Full Code Here

        }

        boolean offered = queue.offer((MessageEvent) e);
        assert offered;

        final Channel channel = ctx.getChannel();
        if (channel.isWritable()) {
            this.ctx = ctx;
            flush(ctx);
        } else if (!channel.isConnected()) {
            this.ctx = ctx;
            discard(ctx);
        }
    }
View Full Code Here

            Channels.fireExceptionCaught(ctx.getChannel(), cause);
        }
    }

    private synchronized void flush(ChannelHandlerContext ctx) throws Exception {
        final Channel channel = ctx.getChannel();
        if (!channel.isConnected()) {
            discard(ctx);
        }

        while (channel.isWritable()) {
            if (currentEvent == null) {
                currentEvent = queue.poll();
            }

            if (currentEvent == null) {
                break;
            }

            if (currentEvent.getFuture().isDone()) {
                // Skip the current request because the previous partial write
                // attempt for the current request has been failed.
                currentEvent = null;
            } else {
                final MessageEvent currentEvent = this.currentEvent;
                Object m = currentEvent.getMessage();
                if (m instanceof ChunkedInput) {
                    ChunkedInput chunks = (ChunkedInput) m;
                    Object chunk;
                    boolean endOfInput;
                    boolean suspend;
                    try {
                        chunk = chunks.nextChunk();
                        endOfInput = chunks.isEndOfInput();
                        if (chunk == null) {
                            chunk = ChannelBuffers.EMPTY_BUFFER;
                            // No need to suspend when reached at the end.
                            suspend = !endOfInput;
                        } else {
                            suspend = false;
                        }
                    } catch (Throwable t) {
                        this.currentEvent = null;

                        currentEvent.getFuture().setFailure(t);
                        fireExceptionCaught(ctx, t);

                        closeInput(chunks);
                        break;
                    }

                    if (suspend) {
                        // ChunkedInput.nextChunk() returned null and it has
                        // not reached at the end of input.  Let's wait until
                        // more chunks arrive.  Nothing to write or notify.
                        break;
                    } else {
                        ChannelFuture writeFuture;
                        if (endOfInput) {
                            this.currentEvent = null;
                            closeInput(chunks);
                            writeFuture = currentEvent.getFuture();
                        } else {
                            writeFuture = future(channel);
                            writeFuture.addListener(new ChannelFutureListener() {
                                @Override
                                public void operationComplete(ChannelFuture future)
                                        throws Exception {
                                    if (!future.isSuccess()) {
                                        currentEvent.getFuture().setFailure(future.getCause());
                                        closeInput((ChunkedInput) currentEvent.getMessage());
                                    }
                                }
                            });
                        }

                        Channels.write(
                                ctx, writeFuture, chunk,
                                currentEvent.getRemoteAddress());
                    }
                } else {
                    this.currentEvent = null;
                    ctx.sendDownstream(currentEvent);
                }
            }

            if (!channel.isConnected()) {
                discard(ctx);
                break;
            }
        }
    }
View Full Code Here

        //System.out.println("WebSocket Client disconnected!");
    }

    @Override
    protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) throws Exception {
        final Channel ch = ctx.channel();
        if (!handshaker.isHandshakeComplete()) {
            // web socket client connected
            handshaker.finishHandshake(ch, (FullHttpResponse) msg);
            handshakeFuture.setSuccess();
            return;
        }

        if (msg instanceof FullHttpResponse) {
            final FullHttpResponse response = (FullHttpResponse) msg;
            throw new Exception("Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content="
                    + response.content().toString(CharsetUtil.UTF_8) + ')');
        }

        // a close frame doesn't mean much here.  errors raised from closed channels will mark the host as dead
        final WebSocketFrame frame = (WebSocketFrame) msg;
        if (frame instanceof TextWebSocketFrame) {
            ctx.fireChannelRead(frame.retain(2));
        } else if (frame instanceof PongWebSocketFrame) {
        } else if (frame instanceof BinaryWebSocketFrame) {
            ctx.fireChannelRead(frame.retain(2));
        } else if (frame instanceof CloseWebSocketFrame)
            ch.close();

    }
View Full Code Here

        }
      }

      // Pick the channel for this scope
      int idx = (Integer.MAX_VALUE & destination.getScope().hashCode()) % channels.size();
      Channel channel = channels.get(idx);
      if (channel == null || !channel.isOpen() || isExpired(channel)) {
        synchronized (channelMap) {
          channel = channels.get(idx);
          if (channel == null || !channel.isOpen() || isExpired(channel)) {
            if (channel != null && channel.isOpen()) {
              channel.close();
            }
            channel = clientBootstrap.connect(destination.getSocketAddress()).sync().channel();
            channels.set(idx, channel);
            statChannelOpen.inc();
            channelOpenTimes.put(channel, System.currentTimeMillis());
          }
        }
      }

      // Compute total length
      int headerLength =
          NUM_LENGTH_FIELDS
              * (Integer.SIZE / 8)
              + (Integer.SIZE / 8)
              * 2 // version, type
              + (Long.SIZE / 8)
              * 2 // 128 bit UUID
              + getLength(destination.getScope().getCluster())
              + getLength(destination.getScope().getResource())
              + getLength(destination.getScope().getPartition())
              + getLength(destination.getScope().getState()) + getLength(config.getInstanceName())
              + getLength(destination.getInstanceName());
      int messageLength = message == null ? 0 : message.readableBytes();

      // Build message header
      ByteBuf headerBuf = channel.alloc().buffer(headerLength);
      headerBuf.writeInt(MESSAGE_VERSION).writeInt(messageType)
          .writeLong(messageId.getMostSignificantBits())
          .writeLong(messageId.getLeastSignificantBits());
      writeStringWithLength(headerBuf, destination.getScope().getCluster());
      writeStringWithLength(headerBuf, destination.getScope().getResource());
      writeStringWithLength(headerBuf, destination.getScope().getPartition());
      writeStringWithLength(headerBuf, destination.getScope().getState());
      writeStringWithLength(headerBuf, config.getInstanceName());
      writeStringWithLength(headerBuf, destination.getInstanceName());

      // Compose message header and payload
      headerBuf.writeInt(messageLength);
      CompositeByteBuf fullByteBuf = channel.alloc().compositeBuffer(2);
      fullByteBuf.addComponent(headerBuf);
      fullByteBuf.writerIndex(headerBuf.readableBytes());
      if (message != null) {
        fullByteBuf.addComponent(message);
        fullByteBuf.writerIndex(fullByteBuf.writerIndex() + message.readableBytes());
      }

      // Send
      statTxMsg.mark();
      statTxBytes.mark(fullByteBuf.readableBytes());
      channel.writeAndFlush(fullByteBuf);
    } catch (Exception e) {
      statError.inc();
      throw new IllegalStateException("Could not send message to " + destination, e);
    }
  }
View Full Code Here

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest req = (FullHttpRequest) msg;
            Channel channel = ctx.channel();
            QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());

            if (!configuration.isAllowCustomRequests()
                    && !queryDecoder.path().startsWith(connectPath)) {
                HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
                channel.write(res).addListener(ChannelFutureListener.CLOSE);
                req.release();
                log.warn("Blocked wrong request! url: {}, ip: {}", queryDecoder.path(), channel.remoteAddress());
                return;
            }

            List<String> sid = queryDecoder.parameters().get("sid");
            if (queryDecoder.path().equals(connectPath)
View Full Code Here

TOP

Related Classes of io.netty.channel.Channel

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.