Java 类io.netty.handler.codec.bytes.ByteArrayDecoder 实例源码

项目:JPRE    文件:TestClient.java   
public void start() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress(this.host, this.port))
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        System.out.println("connected server...");
                        ch.pipeline().addLast(new ByteArrayEncoder());
                        ch.pipeline().addLast(new ByteArrayDecoder());
                        ch.pipeline().addLast(new EchoClientHandler());
                    }
                });

        ChannelFuture cf = b.connect().sync();

        cf.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully().sync();
    }
}
项目:kaa    文件:AbstractKaaTcpServerInitializer.java   
@Override
protected void initChannel(SocketChannel ch) throws Exception {
  final ChannelPipeline p = ch.pipeline();

  final UUID uuid = UUID.randomUUID();

  LOG.debug("KaaTcpServerInitializer Initializing Channel {} connection from {}:{}",
          uuid, ch.remoteAddress().getAddress().toString(), ch.remoteAddress().getPort());

  Attribute<UUID> uuidAttr = ch.attr(AbstractNettyServer.UUID_KEY);
  uuidAttr.set(uuid);

  p.addLast("binaryDecoder", new ByteArrayDecoder());
  p.addLast("kaaTcpDecoder", getDecoder());
  p.addLast("binaryEncoder", new ByteArrayEncoder());
  p.addLast("kaaTcpEncoder", new KaaTcpEncoder());
  p.addLast("mainHandler", getMainHandler(uuid));
  p.addLast("kaaTcpExceptionHandler", new KaaTcpExceptionHandler());
}
项目:sds    文件:NettyServerServiceImpl.java   
@Override
public synchronized void start() {
    bossGroup = new NioEventLoopGroup(); // (1)
    workerGroup = new NioEventLoopGroup();
    try {
        b = new ServerBootstrap(); // (2)
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class) // (3)
                .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {

                        ch.pipeline().addLast(new ByteArrayDecoder());
                        ch.pipeline().addLast(new ByteArrayEncoder());

                        ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));

                        ch.pipeline().addLast(new IdleStateHandler(heartTime, heartTime, heartTime, TimeUnit.SECONDS));

                        ch.pipeline().addLast(new DeliveryHandler(deliveryService));

                    }
                })
                .option(ChannelOption.SO_BACKLOG, 128)          // (5)
                .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

        // Bind and start to accept incoming connections.
        b.bind(settingService.getDeliveryPort());

        logger.info("socket: "+settingService.getDeliveryPort()+" starting....");
        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:Camel    文件:ChannelHandlerFactories.java   
public static ChannelHandlerFactory newByteArrayDecoder(String protocol) {
    if ("udp".equals(protocol)) {
        return new ShareableChannelHandlerFactory(new DatagramPacketByteArrayDecoder());
    } else {
        return new ShareableChannelHandlerFactory(new ByteArrayDecoder());
    }
}
项目:yummy-xml-UI    文件:P2PTunnel.java   
public ChannelInitializerImpl(int command, String message) {
    this.handler_list = new ChannelHandler[]{new CMDFieldPrepender(command), new LengthFieldPrepender(4),
        //new StringEncoder(CommonConstants.UTF8), new StringDecoder(CommonConstants.UTF8),
        new StringEncoder(CommonConstants.UTF8), new ByteArrayDecoder(),
        //new MessageClientHandler(message)};
        new ByteMessageClientHandler(message)};
        //new DelimiterBasedFrameDecoder(2048, Delimiters.lineDelimiter()), 
}
项目:netty-ssl-example    文件:NettySocketClient.java   
public void open(EventLoopGroup eventLoopGroup) throws Exception {
    if (openned.compareAndSet(false, true)) {
        eventloopGroop = eventLoopGroup == null ? new NioEventLoopGroup()
                : eventLoopGroup;
        Bootstrap bootstrap = new Bootstrap();
        final BlockingByteArrayClientHandler handler = new BlockingByteArrayClientHandler(
                this);
        this.clientHandler = handler;
        bootstrap.group(eventloopGroop).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch)
                            throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        SSLEngine engine = SecureSocketSslContextFactory
                                .getClientContext().createSSLEngine();
                        engine.setUseClientMode(true);
                        pipeline.addLast("ssl", new SslHandler(engine));
                        pipeline.addLast("length-decoder",
                                new LengthFieldBasedFrameDecoder(
                                        Integer.MAX_VALUE, 0, 4, 0, 4));
                        pipeline.addLast("bytearray-decoder",
                                new ByteArrayDecoder());
                        pipeline.addLast("length-encoder",
                                new LengthFieldPrepender(4));
                        pipeline.addLast("bytearray-encoder",
                                new ByteArrayEncoder());
                        pipeline.addLast("handler", handler);
                    }

                });
        channelFuture = bootstrap.connect(this.remoteHost, this.remotePort)
                .sync();
    }
}
项目:netty-ssl-example    文件:SecureSocketServerLengthFrameInitializer.java   
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    SSLEngine engine =
        SecureSocketSslContextFactory.getServerContext().createSSLEngine();
    engine.setUseClientMode(false);
    pipeline.addLast("ssl", new SslHandler(engine));  
    pipeline.addLast("length-decoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4)); 
    pipeline.addLast("bytearray-decoder", new ByteArrayDecoder());
    pipeline.addLast("length-encoder", new LengthFieldPrepender(4));  
    pipeline.addLast("bytearray-encoder", new ByteArrayEncoder());
    pipeline.addLast("handler", new SecureSocketServerhandler2());
}
项目:bigio    文件:MeMemberTCP.java   
public GossipServerThread() {
    gossipBossGroup = new NioEventLoopGroup(GOSSIP_BOSS_THREADS);
    gossipWorkerGroup = new NioEventLoopGroup(GOSSIP_WORKER_THREADS);
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(gossipBossGroup, gossipWorkerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.config().setAllocator(UnpooledByteBufAllocator.DEFAULT);
                        ch.pipeline().addLast(new GossipMessageDecoder());
                        ch.pipeline().addLast("encoder", new ByteArrayEncoder());
                        ch.pipeline().addLast("decoder", new ByteArrayDecoder());
                        ch.pipeline().addLast(new GossipMessageHandler());
                        if(LOG.isTraceEnabled()) {
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.TRACE));
                        }
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        LOG.error("Cannot initialize gossip server.", cause);
                    }
                })
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        // Bind and start to accept incoming connections.
        f = b.bind(getIp(), getGossipPort()).sync();
    } catch (InterruptedException ex) {
        LOG.error("Gossip server interrupted.", ex);
    }
}
项目:bigio    文件:MeMemberTCP.java   
public DataServerThread() {
    dataBossGroup = new NioEventLoopGroup(DATA_BOSS_THREADS);
    dataWorkerGroup = new NioEventLoopGroup(DATA_WORKER_THREADS);
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(dataBossGroup, dataWorkerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.config().setAllocator(UnpooledByteBufAllocator.DEFAULT);
                        if(useSSL) {
                            ch.pipeline().addLast(sslContext.newHandler(ch.alloc()));
                        }
                        ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(32768, 0, 2, 0, 2));
                        ch.pipeline().addLast("decoder", new ByteArrayDecoder());
                        ch.pipeline().addLast(new DataMessageHandler());
                        if(LOG.isTraceEnabled()) {
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.TRACE));
                        }
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        LOG.error("Cannot initialize data server.", cause);
                    }
                })
                .option(ChannelOption.SO_SNDBUF, 262144)
                .option(ChannelOption.SO_RCVBUF, 262144)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        // Bind and start to accept incoming connections.
        f = b.bind(getIp(), getDataPort()).sync();
    } catch (InterruptedException ex) {
        LOG.error("Message data interrupted.", ex);
    }
}
项目:bigio    文件:MeMemberUDP.java   
public GossipServerThread() {
    gossipBossGroup = new NioEventLoopGroup(GOSSIP_BOSS_THREADS);
    gossipWorkerGroup = new NioEventLoopGroup(GOSSIP_WORKER_THREADS);
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(gossipBossGroup, gossipWorkerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.config().setAllocator(UnpooledByteBufAllocator.DEFAULT);
                        ch.pipeline().addLast(new GossipMessageDecoder());
                        ch.pipeline().addLast("encoder", new ByteArrayEncoder());
                        ch.pipeline().addLast("decoder", new ByteArrayDecoder());
                        ch.pipeline().addLast(new GossipMessageHandler());
                        if (LOG.isTraceEnabled()) {
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.TRACE));
                        }
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        LOG.error("Cannot initialize gossip server.", cause);
                    }
                })
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        // Bind and start to accept incoming connections.
        f = b.bind(getIp(), getGossipPort()).sync();
    } catch (InterruptedException ex) {
        LOG.error("Gossip server interrupted.", ex);
    }
}
项目:reef    文件:NettyChannelInitializer.java   
@Override
protected void initChannel(final SocketChannel ch) throws Exception {
  ch.pipeline()
      .addLast("frameDecoder", new LengthFieldBasedFrameDecoder(MAXFRAMELENGTH, 0, 4, 0, 4))
      .addLast("bytesDecoder", new ByteArrayDecoder())
      .addLast("frameEncoder", new LengthFieldPrepender(4))
      .addLast("bytesEncoder", new ByteArrayEncoder())
      .addLast("chunker", new ChunkedReadWriteHandler())
      .addLast("handler", handlerFactory.createChannelInboundHandler());
}
项目:uploader    文件:UploadInitializer.java   
@Override
public void initChannel(final SocketChannel ch) throws Exception {
    final ChannelPipeline p = ch.pipeline();

    // add the IP ACL filter first
    if (ipFilter != null) {
        p.addLast("acl", ipFilter);
    }

    if (sslCtx != null) {
        if (configuration.isClientAuth()) {
            final SSLEngine engine = sslCtx.newEngine(ch.alloc());
            engine.setUseClientMode(false);
            engine.setNeedClientAuth(true);

            p.addLast("ssl", new SslHandler(engine));
        } else {
            p.addLast("ssl", sslCtx.newHandler(ch.alloc()));
        }
    }

    // removes idle connections after READER_IDLE_SECONDS seconds
    p.addLast("idleStateHandler",
            new IdleStateHandler(READER_IDLE_SECONDS, 0, 0));

    // authenticate via an ACL and mutual certificates
    p.addLast("auth", new AuthHandler(configuration.isClientAuth()));

    // check to see if the data stream is gzipped or not
    // p.addLast("gzipDetector", new OptionalGzipHandler());

    // break each data chunk by newlines
    p.addLast("line", new LineBasedFrameDecoder(Ints.checkedCast(maxLength),
            true, true));

    // convert each data chunk into a byte array
    p.addLast("decoder", new ByteArrayDecoder());

    // batch and compress chunks of data up to maxUploadBytes
    p.addLast("batcher", new BatchHandler(maxUploadBytes));

    // upload the batch to S3
    p.addLast("uploader", uploadHandler);
}
项目:bigio    文件:RemoteMemberTCP.java   
private void initializeGossipClient() {
    LOG.trace("Initializing gossip client");

    gossipWorkerGroup = new NioEventLoopGroup(GOSSIP_WORKER_THREADS);

    Bootstrap b = new Bootstrap();
    b.group(gossipWorkerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.config().setAllocator(UnpooledByteBufAllocator.DEFAULT);
            ch.pipeline().addLast("encoder", new ByteArrayEncoder());
            ch.pipeline().addLast("decoder", new ByteArrayDecoder());
            ch.pipeline().addLast(new GossipExceptionHandler());
            if(LOG.isTraceEnabled()) {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.TRACE));
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            LOG.error("Cannot initialize gossip client.", cause);
            ctx.close();
        }
    });

    // Start the client.
    ChannelFuture future = b.connect(getIp(), getGossipPort()).awaitUninterruptibly();

    if(future.isCancelled()) {
        gossipChannel = null;
    } else if(!future.isSuccess()) {
        gossipChannel = null;
        retryGossipConnection();
    } else {
        gossipChannel = future.channel();
        setStatus(MemberStatus.Alive);
        updateMember();
    }
}
项目:bigio    文件:RemoteMemberTCP.java   
private void initializeDataClient() {
    LOG.trace("Initializing data client");

    dataWorkerGroup = new NioEventLoopGroup(DATA_WORKER_THREADS);

    Bootstrap b = new Bootstrap();
    b.group(dataWorkerGroup)
     .channel(NioSocketChannel.class)
     .option(ChannelOption.SO_SNDBUF, 262144)
     .option(ChannelOption.SO_RCVBUF, 262144)
     .option(ChannelOption.SO_KEEPALIVE, true)
     .option(ChannelOption.TCP_NODELAY, true)
     .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout)
     .handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.config().setAllocator(UnpooledByteBufAllocator.DEFAULT);
            if(useSSL) {
                ch.pipeline().addLast(sslContext.newHandler(ch.alloc(), ip, dataPort));
            }
            ch.pipeline().addLast("encoder", new ByteArrayEncoder());
            ch.pipeline().addLast("decoder", new ByteArrayDecoder());
            ch.pipeline().addLast(new DataExceptionHandler());
            if(LOG.isTraceEnabled()) {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.TRACE));
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            LOG.error("Cannot initialize data client.", cause);
            ctx.close();
        }
    });

    // Start the client.
    ChannelFuture future = b.connect(getIp(), getDataPort()).awaitUninterruptibly();

    if(future.isCancelled()) {
        dataChannel = null;
    } else if(!future.isSuccess()) {
        dataChannel = null;
        retryDataConnection();
    } else {
        dataChannel = future.channel();

        try {
            dataChannel.closeFuture().sync();
        } catch (InterruptedException ex) {
            LOG.debug("Interrupted waiting for client to shutdown.", ex);
        }
    }
}
项目:bigio    文件:RemoteMemberUDP.java   
private void initializeGossipClient() {
    LOG.trace("Initializing gossip client");

    gossipWorkerGroup = new NioEventLoopGroup(GOSSIP_WORKER_THREADS);

    Bootstrap b = new Bootstrap();
    b.group(gossipWorkerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.config().setAllocator(UnpooledByteBufAllocator.DEFAULT);
            ch.pipeline().addLast("encoder", new ByteArrayEncoder());
            ch.pipeline().addLast("decoder", new ByteArrayDecoder());
            ch.pipeline().addLast(new GossipExceptionHandler());
            if (LOG.isTraceEnabled()) {
                ch.pipeline().addLast(new LoggingHandler(LogLevel.TRACE));
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            LOG.error("Cannot initialize gossip client.", cause);
            ctx.close();
        }
    });

    // Start the client.
    ChannelFuture future = b.connect(getIp(), getGossipPort()).awaitUninterruptibly();

    if (future.isCancelled()) {
        gossipChannel = null;
    } else if (!future.isSuccess()) {
        gossipChannel = null;
        retryGossipConnection();
    } else {
        gossipChannel = future.channel();
        setStatus(MemberStatus.Alive);
        updateMember();
    }
}
项目:sds    文件:SocketServerChannelInitializer.java   
@Override
protected void initChannel(SocketChannel ch) throws Exception {

    logger.debug("initChannel-start");

    ProtocolDecoderService protocolDecoderService = null;
    ProtocolEncoderService protocolEncoderService = null;

    try{
        protocolDecoderService = applicationContext.getBean(ProtocolDecoderService.class);
        protocolEncoderService = applicationContext.getBean(ProtocolEncoderService.class);

    }catch (Exception e){
        protocolDecoderService = new DefaultProtocolDecoderService();
        protocolEncoderService = new DefaultProtocolEncoderService();
    }

    logger.debug("initChannel->protocolDecoderService:"+protocolDecoderService);
    logger.debug("initChannel->protocolEncoderService:"+protocolEncoderService);


    ch.pipeline().addLast(ByteArrayDecoder,new ByteArrayDecoder());
    ch.pipeline().addLast(ByteArrayEncoder,new ByteArrayEncoder());

    ch.pipeline().addLast(LengthFieldBasedFrameDecoder,new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));

    ch.pipeline().addLast(ProtocolDecoderHandler,new ProtocolDecoderHandler(protocolDecoderService));
    ch.pipeline().addLast(ProtocolEncoderHandler,new ProtocolEncoderHandler(protocolEncoderService));


    ch.pipeline().addLast(SystemTimeOut,new IdleStateHandler(heartTime, heartTime, heartTime, TimeUnit.SECONDS));

    ch.pipeline().addLast(SocketHandler,new SocketHandler(socketService));

    logger.debug("initChannel-end");
}