@Override
 public void initChannel(SocketChannel ch) throws Exception {
   ChannelPipeline p = ch.pipeline();
   p.addLast("encoder", new HttpResponseEncoder());
   p.addLast("decoder", new HttpRequestDecoder(4096, 8192, 8192, false));
   p.addLast("handler", new HelloServerHandler(service));
 }
  /**
   * 채널 파이프라인 설정. Netty.Server.Configuration.NettyServerConfiguration 에서 등록한 Bean 을 이용해 사용자의 통신을 처리할
   * Handler 도 등록. Netty.Server.Handler.JsonHandler 에서 실제 사용자 요청 처리.
   *
   * @param channel
   * @throws Exception
   */
  @Override
  protected void initChannel(Channel channel) throws Exception {

    ChannelPipeline channelPipeline = channel.pipeline();

    switch (transferType) {
      case "websocket":
        channelPipeline
            .addLast(new HttpServerCodec())
            .addLast(new HttpObjectAggregator(65536))
            .addLast(new WebSocketServerCompressionHandler())
            .addLast(
                new WebSocketServerProtocolHandler(
                    transferWebsocketPath,
                    transferWebsocketSubProtocol,
                    transferWebsocketAllowExtensions))
            .addLast(new LoggingHandler(LogLevel.valueOf(logLevelPipeline)))
            .addLast(websocketHandler);

      case "tcp":
      default:
        channelPipeline
            .addLast(new LineBasedFrameDecoder(Integer.MAX_VALUE))
            .addLast(STRING_DECODER)
            .addLast(STRING_ENCODER)
            .addLast(new LoggingHandler(LogLevel.valueOf(logLevelPipeline)))
            .addLast(jsonHandler);
    }
  }
示例#3
0
  /**
   * The lifecycle is as follow: first message ever received or transmitted is a handshake. It will
   * come from both side The handle must therefore be specialized.
   *
   * @param ch The socket chanel connected to the remote peer.
   * @throws Exception
   */
  @Override
  public void initChannel(final SocketChannel ch) throws Exception {

    ChannelPipeline pipeline = ch.pipeline();
    PeerWire peerWire = new PeerWire(ch);

    pipeline.addLast(
        "handshakeDecoder",
        new PwpHandshakeDecoder() {
          @Override
          public void channelActive(ChannelHandlerContext ctx) throws Exception {
            super.channelActive(ctx);

            // The new peerwire can only be sent to the rest of the application after the socket has
            // been connected
            // successfully
            eventBus.post(new NewPeerWireEvent(peerWire));
          }
        });

    pipeline.addLast(new ByteArrayDecoder());

    pipeline.addLast(new PwpChannelHandler(peerWire));
    pipeline.addLast(new ByteArrayEncoder());
  }
示例#4
0
  @Override
  protected void doBeginRead() throws Exception {
    if (readInProgress) {
      return;
    }

    ChannelPipeline pipeline = pipeline();
    Queue<Object> inboundBuffer = this.inboundBuffer;
    if (inboundBuffer.isEmpty()) {
      readInProgress = true;
      return;
    }

    final Integer stackDepth = READER_STACK_DEPTH.get();
    if (stackDepth < MAX_READER_STACK_DEPTH) {
      READER_STACK_DEPTH.set(stackDepth + 1);
      try {
        for (; ; ) {
          Object received = inboundBuffer.poll();
          if (received == null) {
            break;
          }
          pipeline.fireChannelRead(received);
        }
        pipeline.fireChannelReadComplete();
      } finally {
        READER_STACK_DEPTH.set(stackDepth);
      }
    } else {
      eventLoop().execute(readTask);
    }
  }
 static void removeIfExists(
     ChannelPipeline pipeline, Class<? extends ChannelHandler> handlerClass) {
   ChannelHandler channelHandler = pipeline.get(handlerClass);
   if (channelHandler != null) {
     pipeline.remove(channelHandler);
   }
 }
 @Override
 protected void initChannel(SocketChannel ch) throws Exception {
   ChannelPipeline pipeline = ch.pipeline();
   pipeline.addLast("decoder", messageDecode);
   pipeline.addLast("handler", serverHandler);
   pipeline.addLast("encoder", messageEncode);
 }
 @Override
 public void initChannel(SocketChannel socketChannel) throws Exception {
   ChannelPipeline p = socketChannel.pipeline();
   p.addLast(new SocksInitRequestDecoder());
   p.addLast(socksMessageEncoder);
   p.addLast(socksServerHandler);
 }
  @Override
  public void enableChannel(NetConnectionType connectionType, Channel ch) throws Exception {
    if (null == connectionType) return;
    if (null == ch) return;

    ChannelPipeline pipeline = ch.pipeline();

    switch (connectionType) {
      case NODE_IN_AGENT_CHAT:
      case NODE_IN_AGENT_LOGINSERVER:
      case NODE_IN_AGENT_NPC:
      case NODE_IN_AGENT_SCENE:
        logger.info("{} add agent codec", ch);

        // pipeline.addBefore(DEFAULT_DECODER_LENGTH, AGENT_PACKET_DECODER_LENGTH, new
        // LengthFieldBasedFrameDecoder(2048,0, 4/** ,0,4*/));
        pipeline.addBefore(
            DEFAULT_DECODER_LENGTH, AGENT_PACKET_DECODER, new AgentNettyDecoder(netServiceHandler));

        pipeline.addBefore(
            DEFAULT_ENCODER_LENGTH_APPENDER, AGENT_PACKET_ENCODER, new AgentNettyEncoder());
        // pipeline.addBefore(DEFAULT_ENCODER_LENGTH_APPENDER, AGENT_PACKET_ENCODER_LENGTH_APPENDER,
        // new LengthFieldPrepender(4));

        break;
      default:
        break;
    }
  }
 @Override
 public void initChannel(SocketChannel ch) {
   ChannelPipeline p = ch.pipeline();
   p.addLast(new HttpServerCodec());
   p.addLast(new HttpObjectAggregator(1048576));
   p.addLast(new GithubAuthHandler(githubService, appConfig));
   p.addLast(new DocProxyHandler(s3Service, appConfig));
 }
示例#10
0
 @Override
 public void initChannel(SocketChannel ch) throws Exception {
   ChannelPipeline pipeline = ch.pipeline();
   pipeline.addLast("encoder", new HttpResponseEncoder());
   pipeline.addLast("decoder", new HttpRequestDecoder());
   pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
   pipeline.addLast("handler", new AutobahnServerHandler());
 }
示例#11
0
    @Override
    public void initChannel(SocketChannel ch) throws Exception {
      ChannelPipeline pipeline = ch.pipeline();

      pipeline.addLast("http-codec", new HttpServerCodec());
      //            pipeline.addLast("log", new LoggingHandler(LogLevel.INFO));

      pipeline.addLast("handler", new RFRequestHandler());
    }
  private static void ensureThatExceptionHandlerIsLast(ChannelPipeline pipeline) {
    ChannelInboundHandler exceptionHandler = ChannelExceptionHandler.getInstance();
    if (pipeline.last() != exceptionHandler || pipeline.context(exceptionHandler) == null) {
      return;
    }

    pipeline.remove(exceptionHandler);
    pipeline.addLast(exceptionHandler);
  }
  @AdviseWith(adviceClasses = NettyUtilAdvice.class)
  @NewEnv(type = NewEnv.Type.CLASSLOADER)
  @Test
  public void testExecute() throws Exception {
    EmbeddedChannel embeddedChannel = NettyTestUtil.createEmptyEmbeddedChannel();

    ChannelPipeline channelPipeline = embeddedChannel.pipeline();

    channelPipeline.addFirst(NettyRPCChannelHandler.NAME, NettyRPCChannelHandler.INSTANCE);

    NettyChannelAttributes.putFabricWorker(
        embeddedChannel,
        0,
        new LocalFabricWorker<Serializable>(
            new EmbeddedProcessChannel<Serializable>(new DefaultNoticeableFuture<Serializable>())));

    ProcessCallableExecutor processCallableExecutor =
        new NettyFabricWorkerProcessCallableExecutor(embeddedChannel, 0, Long.MAX_VALUE);

    NoticeableFuture<Serializable> noticeableFuture =
        processCallableExecutor.execute(
            new ProcessCallable<Serializable>() {

              @Override
              public Serializable call() {
                return StringPool.BLANK;
              }
            });

    embeddedChannel.writeInbound(embeddedChannel.readOutbound());
    embeddedChannel.writeInbound(embeddedChannel.readOutbound());

    Assert.assertEquals(StringPool.BLANK, noticeableFuture.get());

    final ProcessException processException = new ProcessException("");

    noticeableFuture =
        processCallableExecutor.execute(
            new ProcessCallable<Serializable>() {

              @Override
              public Serializable call() throws ProcessException {
                throw processException;
              }
            });

    embeddedChannel.writeInbound(embeddedChannel.readOutbound());
    embeddedChannel.writeInbound(embeddedChannel.readOutbound());

    try {
      noticeableFuture.get();

      Assert.fail();
    } catch (ExecutionException ee) {
      Assert.assertSame(processException, ee.getCause());
    }
  }
  @Override
  protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline p = ch.pipeline();

    // p.addLast(new LoggingHandler(LogLevel.INFO));
    p.addLast(new ObjectEncoder());
    p.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));

    p.addLast(clientMtMapRequestAdapter);
  }
示例#15
0
 @Override
 public void initChannel(SocketChannel ch) {
   ChannelPipeline p = ch.pipeline();
   if (sslCtx != null) {
     p.addLast(sslCtx.newHandler(ch.alloc()));
   }
   p.addLast(new HttpClientCodec());
   p.addLast(new HttpContentDecompressor());
   p.addLast(handler);
 }
 @Override
 public void initChannel(SocketChannel ch) throws Exception {
   ChannelPipeline pipeline = ch.pipeline();
   if (sslCtx != null) {
     pipeline.addLast(sslCtx.newHandler(ch.alloc()));
   }
   pipeline.addLast(new HttpServerCodec());
   pipeline.addLast(new HttpObjectAggregator(65536));
   pipeline.addLast(new WebSocketServerHandler());
 }
示例#17
0
 protected void addHttpHandlers(ChannelHandlerContext var1) {
   ChannelPipeline var2 = var1.pipeline();
   var2.addLast((String) "httpRequestDecoder", (ChannelHandler) (new HttpRequestDecoder()));
   var2.addLast((String) "httpResponseEncoder", (ChannelHandler) (new HttpResponseEncoder()));
   var2.addLast(
       (String) "httpChunkAggregator",
       (ChannelHandler) (new HttpObjectAggregator(this.maxHttpContentLength)));
   var2.addLast(
       (String) "httpRequestHandler", (ChannelHandler) this.createHttpRequestHandlerForHttp());
 }
 @Override
 public ChannelPipeline getPipeline() throws Exception {
   // Create a default pipeline implementation.
   ChannelPipeline pipeline = pipeline();
   pipeline.addLast("decoder", new HttpRequestDecoder());
   pipeline.addLast("aggregator", new HttpChunkAggregator(65536));
   pipeline.addLast("encoder", new HttpResponseEncoder());
   pipeline.addLast("handler", new AutobahnServerHandler());
   return pipeline;
 }
    @Override
    protected void initChannel(Channel ch) throws Exception {
      ChannelPipeline pipeline = ch.pipeline();

      pipeline.addLast(new ClientStateHandler(m_descriptor.getName()));

      for (Map.Entry<String, ChannelHandler> e : m_descriptor.getHandlers().entrySet()) {
        pipeline.addLast(e.getKey(), e.getValue());
      }
    }
示例#20
0
    @Override
    protected void initChannel(Channel channel) throws Exception {
      ChannelPipeline pipeline = channel.pipeline();

      int maxChunkSize = conf.getIntVar(TajoConf.ConfVars.SHUFFLE_FETCHER_CHUNK_MAX_SIZE);
      int readTimeout = conf.getIntVar(TajoConf.ConfVars.SHUFFLE_FETCHER_READ_TIMEOUT);

      pipeline.addLast("codec", new HttpClientCodec(4096, 8192, maxChunkSize));
      pipeline.addLast("inflater", new HttpContentDecompressor());
      pipeline.addLast("timeout", new ReadTimeoutHandler(readTimeout, TimeUnit.SECONDS));
      pipeline.addLast("handler", new HttpClientHandler(file));
    }
示例#21
0
  @Override
  public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add the text line codec combination first,
    pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast("decoder", DECODER);
    pipeline.addLast("encoder", ENCODER);

    // and then business logic.
    pipeline.addLast("handler", CLIENTHANDLER);
  }
  @Override
  public void initChannel(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();

    // Add the text line codec combination first,
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(DECODER);
    pipeline.addLast(ENCODER);

    // and then business logic.
    pipeline.addLast(CLIENT_HANDLER);
  }
示例#23
0
 @Override
 public void run() {
   ChannelPipeline pipeline = pipeline();
   for (; ; ) {
     Object m = inboundBuffer.poll();
     if (m == null) {
       break;
     }
     pipeline.fireChannelRead(m);
   }
   pipeline.fireChannelReadComplete();
 }
示例#24
0
 private static void finishPeerRead(LocalChannel peer, ChannelPipeline peerPipeline) {
   if (peer.readInProgress) {
     peer.readInProgress = false;
     for (; ; ) {
       Object received = peer.inboundBuffer.poll();
       if (received == null) {
         break;
       }
       peerPipeline.fireChannelRead(received);
     }
     peerPipeline.fireChannelReadComplete();
   }
 }
示例#25
0
  @Override
  public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add the text line codec combination first,
    pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    // the encoder and decoder are static as these are sharable
    pipeline.addLast("decoder", DECODER);
    pipeline.addLast("encoder", ENCODER);
    nhs.server = new TelnetServer();
    nhs.server.server = nhs;
    // and then business logic.
    pipeline.addLast("handler", nhs.server);
  }
示例#26
0
  @Override
  protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // 以("\n")为结尾分割的 解码器
    pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));

    // 字符串解码 和 编码
    pipeline.addLast("decoder", new StringDecoder());
    pipeline.addLast("encoder", new StringEncoder());

    // 自己的逻辑Handler
    pipeline.addLast("handler", new HelloServerHandler());
  }
  @Test
  public void testExecute() throws Exception {
    EmbeddedChannel embeddedChannel = NettyTestUtil.createEmptyEmbeddedChannel();

    ChannelPipeline channelPipeline = embeddedChannel.pipeline();

    channelPipeline.addFirst(NettyRPCChannelHandler.NAME, NettyRPCChannelHandler.INSTANCE);

    ProcessCallableExecutor processCallableExecutor =
        new NettyFabricAgentProcessCallableExecutor(embeddedChannel);

    NoticeableFuture<Serializable> noticeableFuture =
        processCallableExecutor.execute(
            new ProcessCallable<Serializable>() {

              @Override
              public Serializable call() {
                return StringPool.BLANK;
              }
            });

    embeddedChannel.writeInbound(embeddedChannel.readOutbound());
    embeddedChannel.writeInbound(embeddedChannel.readOutbound());

    Assert.assertEquals(StringPool.BLANK, noticeableFuture.get());

    final ProcessException processException = new ProcessException("");

    noticeableFuture =
        processCallableExecutor.execute(
            new ProcessCallable<Serializable>() {

              @Override
              public Serializable call() throws ProcessException {
                throw processException;
              }
            });

    embeddedChannel.writeInbound(embeddedChannel.readOutbound());
    embeddedChannel.writeInbound(embeddedChannel.readOutbound());

    try {
      noticeableFuture.get();

      Assert.fail();
    } catch (ExecutionException ee) {
      Assert.assertSame(processException, ee.getCause());
    }
  }
示例#28
0
  @Override
  public void send(final InputStream stream) throws Exception {
    byte[] chunk = new byte[bufferSize];
    int count = ByteStreams.read(stream, chunk, 0, bufferSize);
    if (count <= 0) {
      return;
    }
    ByteBuf buffer = Unpooled.wrappedBuffer(chunk, 0, count);
    if (count < bufferSize) {
      send(buffer);
    } else {
      DefaultHttpResponse rsp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);

      if (!headers.contains(HttpHeaderNames.CONTENT_LENGTH)) {
        headers.set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
      } else {
        if (keepAlive) {
          headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        }
      }

      // dump headers
      rsp.headers().set(headers);
      ChannelHandlerContext ctx = this.ctx;
      ctx.attr(NettyRequest.NEED_FLUSH).set(false);

      // add chunker
      ChannelPipeline pipeline = ctx.pipeline();
      if (pipeline.get("chunker") == null) {
        pipeline.addAfter("encoder", "chunker", new ChunkedWriteHandler());
      }

      // group all write
      ctx.channel()
          .eventLoop()
          .execute(
              () -> {
                // send headers
                ctx.write(rsp);
                // send head chunk
                ctx.write(buffer);
                // send tail
                ctx.write(new ChunkedStream(stream, bufferSize));
                keepAlive(ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT));
              });
    }

    committed = true;
  }
  @Override
  protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine();
    engine.setUseClientMode(false);

    pipeline.addLast("ssl", new SslHandler(engine));

    pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast("decoder", new StringDecoder());
    pipeline.addLast("encoder", new StringEncoder());

    // and then business logic.
    pipeline.addLast("handler", new SecureChatServerHandler());
  }
 private void serve0(final LocalChannel child) {
   inboundBuffer.add(child);
   if (acceptInProgress) {
     acceptInProgress = false;
     ChannelPipeline pipeline = pipeline();
     for (; ; ) {
       Object m = inboundBuffer.poll();
       if (m == null) {
         break;
       }
       pipeline.fireChannelRead(m);
     }
     pipeline.fireChannelReadComplete();
   }
 }