io.netty.handler.codec.bytes.ByteArrayDecoder #io.netty.handler.codec.bytes.ByteArrayEncoder源码实例Demo

下面列出了 io.netty.handler.codec.bytes.ByteArrayDecoder #io.netty.handler.codec.bytes.ByteArrayEncoder 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: krpc   文件: TCPClient.java

/**
 * 初始化Bootstrap
 * 
 * @return
 */
public  Bootstrap getBootstrap() {
	EventLoopGroup group = new NioEventLoopGroup();
	Bootstrap b = new Bootstrap();
	b.group(group).channel(NioSocketChannel.class);
	TcpClientHandler tcpClientHandler = new TcpClientHandler(TCPClient.this);
	b.handler(new ChannelInitializer<Channel>() {
		@Override
		protected void initChannel(Channel ch) throws Exception {
			ChannelPipeline pipeline = ch.pipeline();
			pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
			pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
			pipeline.addLast("decoder", new ByteArrayDecoder());
			pipeline.addLast("encoder", new ByteArrayEncoder());
			pipeline.addLast("handler", tcpClientHandler);
		}
	});
	return b;
}
 
源代码2 项目: krpc   文件: TCPClient.java

/**
 * 初始化Bootstrap
 * 
 * @return
 */
public static final Bootstrap getBootstrap() {
	EventLoopGroup group = new NioEventLoopGroup();
	Bootstrap b = new Bootstrap();
	b.group(group).channel(NioSocketChannel.class);
	b.handler(new ChannelInitializer<Channel>() {
		@Override
		protected void initChannel(Channel ch) throws Exception {
			ChannelPipeline pipeline = ch.pipeline();
			pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
			pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
			pipeline.addLast("decoder", new ByteArrayDecoder());
			pipeline.addLast("encoder", new ByteArrayEncoder());
			pipeline.addLast("handler", new TcpClientHandler());
		}
	});
	return b;
}
 
源代码3 项目: krpc   文件: TcpServer.java

protected static void run() throws Exception {
		ServerBootstrap b = new ServerBootstrap();
		b.group(bossGroup, workerGroup);
		b.channel(NioServerSocketChannel.class);
		b.childHandler(new ChannelInitializer<SocketChannel>() {
			@Override
			public void initChannel(SocketChannel ch) throws Exception {
				ChannelPipeline pipeline = ch.pipeline();
				pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
				pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
				pipeline.addLast("decoder", new ByteArrayDecoder());
				pipeline.addLast("encoder", new ByteArrayEncoder());
//				pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
//				pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
				pipeline.addLast(new TcpServerHandler());
			}
		});

		// b.bind(IP, PORT).sync();
		ChannelFuture f = b.bind(PORT).sync(); // (7)

		f.channel().closeFuture().sync();

		System.out.println("TCP服务器已启动");
	}
 

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ClientSession clientSession =
            oneNetServerContext.getOneNetConnectionManager().getAvailableSession(
                    oneNetServerContext.getOneNetServerContextConfig().getContextName());
    if (!clientSession.isActive()) {
        ch.close();
        log.info(String.format("Can't found %s's client session.",oneNetServerContext.getOneNetServerContextConfig().getContextName()));
    } else {
        OneNetSession oneNetSession = oneNetServerContext.createSession(ch, clientSession);
        int bytePreSecond = oneNetServerContext.getOneNetServerContextConfig().getKBps() * OneNetCommonConstants.KByte;
        log.debug("Session create:"+oneNetSession.toString());
        ch.pipeline()
                .addLast(new ChannelTrafficShapingHandler(bytePreSecond,
                        bytePreSecond))
                .addLast(new InternetChannelInboundHandler(oneNetServerContext, oneNetSession))
                .addLast(new ByteArrayEncoder());
    }
}
 
源代码5 项目: one-net   文件: LocalChannelInitializer.java

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline p = ch.pipeline();
    int bytesPreSecond = 0;
    if (clientSession != null) {
        bytesPreSecond = oneNetClientContext.getKBps() * OneNetCommonConstants.KByte;
    }
    p.addLast(new WriteTimeoutHandler(5))
            .addLast(CHANNEL_TRAFFIC_HANDLER, new ChannelTrafficShapingHandler(bytesPreSecond,
            bytesPreSecond))
            .addLast(LOCAL_RESPONSE_HANDLER, new LocalInboudHandler(oneNetClientContext, clientSession))
            .addLast(new ByteArrayEncoder());
}
 
源代码6 项目: one-net   文件: HttpChannelInitializer.java

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    int bytePreSecond = 5 * OneNetCommonConstants.KByte;
    ch.pipeline()
            .addLast(trafficHandler, new ChannelTrafficShapingHandler(bytePreSecond,
                    bytePreSecond))
            .addLast(new HttpChannelInboundHandler())
            .addLast(new ByteArrayEncoder());

}
 
源代码7 项目: 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();
    }
}
 
源代码8 项目: 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());
}
 
源代码9 项目: krpc   文件: BootStrap.java

public static void main(String[] args) {
    try {
        if (args.length > 0) {
            // 初始化项目路径
            String serviceName = args[0];
            if (args.length == 2) {
                Global.getInstance().setPort(Integer.parseInt(args[1]));
            }

            Global.getInstance().setServiceName(serviceName);
            String userDir = System.getProperty("user.dir");
            String rootPath = userDir + File.separator + ".." + File.separator;
            String rootLibPath = userDir + File.separator + "lib";

            String serviceRootPath = rootPath + "service" + File.separator + serviceName + File.separator;

            // 初始化log4j
            DOMConfigurator.configure(serviceRootPath + File.separator + "conf" + File.separator + "log4j.xml");
            Logger log = LoggerFactory.getLogger(BootStrap.class);

            // 加载配置文件,并初始化相关内容
            LoadConfigure.load(serviceRootPath);

            // 启动netty server
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            ServerBootstrap bootstrap = new ServerBootstrap();


            bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                            pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                            pipeline.addLast("decoder", new ByteArrayDecoder());
                            pipeline.addLast("encoder", new ByteArrayEncoder());
                            pipeline.addLast(new ServerHandler());
                        }
                    }).option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, Global.getInstance().getMaxBuf(), Global.getInstance().getMaxBuf()));


            ChannelFuture f = bootstrap.bind(Global.getInstance().getPort()).sync();
            /**
             * 使用注册中心
             */
            if (Global.getInstance().getZookeeperInfo() != null) {
                ZkRegisterCenter.register();
            }


            log.info("启动成功,监听端口:" + Global.getInstance().getPort());
            f.channel().closeFuture().sync();


        } else {
            System.out.println("请输入启动的服务名字");
        }

    } catch (Exception e) {
        System.out.println("启动失败");
        e.printStackTrace();
    }

}
 

@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");
}