io.netty.handler.codec.bytes.ByteArrayDecoder Java Examples

The following examples show how to use io.netty.handler.codec.bytes.ByteArrayDecoder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TCPClient.java    From krpc with MIT License 6 votes vote down vote up
/**
 * 初始化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;
}
 
Example #2
Source File: TCPClient.java    From krpc with MIT License 6 votes vote down vote up
/**
 * 初始化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;
}
 
Example #3
Source File: TcpServer.java    From krpc with MIT License 6 votes vote down vote up
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服务器已启动");
	}
 
Example #4
Source File: NettyServerServiceImpl.java    From sds with Apache License 2.0 5 votes vote down vote up
@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();
    }
}
 
Example #5
Source File: NettyChannelInitializer.java    From reef with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #6
Source File: BootStrap.java    From krpc with MIT License 4 votes vote down vote up
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();
    }

}
 
Example #7
Source File: NettyTCPChannelInitializer.java    From pulsar with Apache License 2.0 4 votes vote down vote up
@Override
protected void initChannel(Channel channel) throws Exception {
    channel.pipeline().addLast(new ByteArrayDecoder());
    channel.pipeline().addLast(this.handler);
}
 
Example #8
Source File: SocketServerChannelInitializer.java    From sds with Apache License 2.0 3 votes vote down vote up
@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");
}