io.netty.handler.codec.string.StringEncoder Java Examples

The following examples show how to use io.netty.handler.codec.string.StringEncoder. 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: NettyClient.java    From netty-learning with Apache License 2.0 7 votes vote down vote up
public void connect(String host, int port) throws InterruptedException {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {

                        ch.pipeline().addLast(new FixedLengthFrameDecoder(1<<5));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new StringEncoder());

                        ch.pipeline().addLast(new ClientHandler());
                    }
                });

        ChannelFuture future = b.connect(host, port).sync();

        future.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example #2
Source File: SecureChatServerInitializer.java    From netty-4.1.22 with Apache License 2.0 7 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    pipeline.addLast(sslCtx.newHandler(ch.alloc()));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // and then business logic.
    pipeline.addLast(new SecureChatServerHandler());
}
 
Example #3
Source File: Receiver.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {
		@Override
		public void initChannel(SocketChannel ch) throws Exception {
			ChannelPipeline p = ch.pipeline();
			p.addLast(new StringEncoder());
			p.addLast(new StringDecoder());
			p.addLast(new ChannelInboundHandlerAdapter() {
				@Override
				public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
					System.out.println(msg);
					ctx.close();
				}
			});
		}
	};
	BootstrapTemplate.newServerBootstrap(HOST, PORT, initializer);
}
 
Example #4
Source File: SecureChatServerInitializer.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    pipeline.addLast(sslCtx.newHandler(ch.alloc()));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // and then business logic.
    pipeline.addLast(new SecureChatServerHandler());
}
 
Example #5
Source File: NettyClientDemo5.java    From java-study with Apache License 2.0 6 votes vote down vote up
/**
		 * Netty创建全部都是实现自AbstractBootstrap。
		 * 客户端的是Bootstrap,服务端的则是ServerBootstrap。
		 **/
	    public static void main(String[] args) throws InterruptedException, IOException { 
	        	 b.group(group)  
	             .channel(NioSocketChannel.class)  
	             .option(ChannelOption.TCP_NODELAY,true)  
	             .handler(new ChannelInitializer<SocketChannel>() {  
	                 @Override  
	                 public void initChannel(SocketChannel ch) throws Exception {  
	                     ChannelPipeline p = ch.pipeline();  
	                     //入参说明: 读超时时间、写超时时间、所有类型的超时时间、时间格式
	                     //因为服务端设置的超时时间是5秒,所以设置4秒
	                     p.addLast( new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS));  
	                     p.addLast( new StringDecoder());  
	                     p.addLast( new StringEncoder());  
	                     p.addLast(new NettyClientHandlerDemo5());   //绑定自定义业务 
	                 }  
	             });  
	            // 连接服务端
	            ch = b.connect(host, port).sync().channel();
	            System.out.println("客户端成功启动...");
	            //发送消息
//	            star();
	    }
 
Example #6
Source File: SecureChatClientInitializer.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    pipeline.addLast(sslCtx.newHandler(ch.alloc(), SecureChatClient.HOST, SecureChatClient.PORT));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // and then business logic.
    pipeline.addLast(new SecureChatClientHandler());
}
 
Example #7
Source File: RxtxClient.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventLoopGroup group = new OioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(RxtxChannel.class)
         .handler(new ChannelInitializer<RxtxChannel>() {
             @Override
             public void initChannel(RxtxChannel ch) throws Exception {
                 ch.pipeline().addLast(
                     new LineBasedFrameDecoder(32768),
                     new StringEncoder(),
                     new StringDecoder(),
                     new RxtxClientHandler()
                 );
             }
         });

        ChannelFuture f = b.connect(new RxtxDeviceAddress(PORT)).sync();

        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example #8
Source File: Receiver.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {
		@Override
		public void initChannel(SocketChannel ch) throws Exception {
			ChannelPipeline p = ch.pipeline();
			p.addLast(new StringEncoder());
			p.addLast(new StringDecoder());
			p.addLast(new ChannelInboundHandlerAdapter() {
				@Override
				public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
					System.out.println(msg);
					ctx.close();
				}
			});
		}
	};
	BootstrapTemplate.newServerBootstrap(HOST, PORT, initializer);
}
 
Example #9
Source File: SecureChatServerInitializer.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    pipeline.addLast(createSslHandler(initSSLContext()));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // and then business logic.
    pipeline.addLast(new SecureChatServerHandler());
}
 
Example #10
Source File: SecureChatClientInitializer.java    From julongchain with Apache License 2.0 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // 添加SSL用于加密每一个步骤.
    // 在本次演示中我们在服务端使用了一张虚拟的证书,可以接收任何有效的客户端证书.
    // 但在真实场景中你需要一个更复杂的客户端和服务端标记.
    pipeline.addLast(sslCtx.newHandler(ch.alloc(), SecureChatClient.HOST, SecureChatClient.PORT));

    // SSL之上添加编解码处理.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // 处理业务逻辑.
    pipeline.addLast(new SecureChatClientHandler());
}
 
Example #11
Source File: SecureChatServerInitializer.java    From julongchain with Apache License 2.0 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // 添加SSL用于加密每一个步骤.
    // 在本次演示中我们在服务端使用了一张虚拟的证书,可以接收任何有效的客户端证书.
    // 但在真实场景中你需要一个更复杂的客户端和服务端标记.
    pipeline.addLast(sslCtx.newHandler(ch.alloc()));

    // SSL之上添加编解码处理.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // 处理业务逻辑.
    pipeline.addLast(new SecureChatServerHandler());
}
 
Example #12
Source File: EmbeddedRedisInitializer.java    From dyno with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(final SocketChannel ch) throws Exception {
    final ChannelPipeline pipeline = ch.pipeline();

    if (useSsl) {
        final SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
        sslEngine.getNeedClientAuth();

        pipeline.addLast("sslHandler", new SslHandler(sslEngine));
    }


    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    pipeline.addLast(new MockedResponseHandler(response));
}
 
Example #13
Source File: OvsdbChannelInitializer.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel channel) throws Exception {

    ChannelPipeline pipeline = channel.pipeline();
    if (sslContext != null) {
        log.info("OVSDB SSL enabled.");
        SSLEngine sslEngine = sslContext.createSSLEngine();

        sslEngine.setNeedClientAuth(true);
        sslEngine.setUseClientMode(false);
        sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
        sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
        sslEngine.setEnableSessionCreation(true);

        SslHandler sslHandler = new SslHandler(sslEngine);
        pipeline.addLast("ssl", sslHandler);
    } else {
        log.info("OVSDB SSL disabled.");
    }
    pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
    pipeline.addLast(new MessageDecoder());

    pipeline.addLast(new IdleStateHandler(READER_IDLE_TIME, WRITER_IDLE_TIME, ALL_IDLE_TIME));
    pipeline.addLast(new ReadTimeoutHandler(TIMEOUT));
    controller.handleNewNodeConnection(channel);
}
 
Example #14
Source File: Server.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workGroup = new NioEventLoopGroup();
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,100)
            .handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new StringEncoder());
                    pipeline.addLast(new StringDecoder());
                    pipeline.addLast(new ServerHandler());
                }
            });
    ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress("172.28.86.151",8080)).sync();
    channelFuture.channel().closeFuture().sync();
    bossGroup.shutdownGracefully();
    workGroup.shutdownGracefully();
}
 
Example #15
Source File: RxtxClient.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventLoopGroup group = new OioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(RxtxChannel.class)
         .handler(new ChannelInitializer<RxtxChannel>() {
             @Override
             public void initChannel(RxtxChannel ch) throws Exception {
                 ch.pipeline().addLast(
                     new LineBasedFrameDecoder(32768),
                     new StringEncoder(),
                     new StringDecoder(),
                     new RxtxClientHandler()
                 );
             }
         });

        ChannelFuture f = b.connect(new RxtxDeviceAddress(PORT)).sync();

        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example #16
Source File: SecureChatClientInitializer.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    pipeline.addLast(sslCtx.newHandler(ch.alloc(), SecureChatClient.HOST, SecureChatClient.PORT));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // and then business logic.
    pipeline.addLast(new SecureChatClientHandler());
}
 
Example #17
Source File: DelimiterServer.java    From netty-learning with Apache License 2.0 5 votes vote down vote up
public void bind(int port) throws Exception {

		EventLoopGroup bossGroup = new NioEventLoopGroup(1);
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
			.channel(NioServerSocketChannel.class)
			.option(ChannelOption.SO_BACKLOG, 1024)
			.childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				public void initChannel(SocketChannel ch) throws Exception {

					ChannelPipeline p = ch.pipeline();
					p.addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer(Constants.DELIMITER.getBytes())));
					p.addLast(new StringDecoder());
					p.addLast(new StringEncoder());

					p.addLast(new DelimiterServerHandler());
				}
			});

			// Bind and start to accept incoming connections.
			ChannelFuture f = b.bind(port).sync(); // (7)

			logger.info("server bind port:{}", port);

			// Wait until the server socket is closed.
			f.channel().closeFuture().sync();

		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
 
Example #18
Source File: Controller.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel channel) throws Exception {
    log.info("New channel created");
    channel.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
    channel.pipeline().addLast(new MessageDecoder());
    handleNewNodeConnection(channel);

}
 
Example #19
Source File: JumbuneAgentDecoder.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Invoke log files receive handler.
 *
 * @param ctx the ctx
 */
private void invokeLogFilesReceiveHandlerForHA(ChannelHandlerContext ctx) {
	ChannelPipeline p = ctx.pipeline();		
	EventExecutor e1 = new DefaultEventExecutorGroup(1).next();
	p.addLast("stringDecoder", new StringDecoder());
	p.addLast("delegator", new Delegator(receiveDirectory));
	p.addLast(HEARTBEAT_HANDLER, new HeartbeatHandler(JumbuneAgent.getHeartBeatMillis(), 
			JumbuneAgent.getHeartBeatMillis(), JumbuneAgent.getHeartBeatMillis()));
	p.addLast("stringEncoder", new StringEncoder());
	p.addLast(e1, new LogFilesEncoder());
	p.remove(this);
}
 
Example #20
Source File: JumbuneAgentDecoder.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Invoke log files send handler.
 *
 * @param ctx the ctx
 */
private void invokeLogFilesSendHandler(ChannelHandlerContext ctx) {
	ChannelPipeline p = ctx.pipeline();
	
	p.addLast(STREAMER, new LogFilesDecoder(receiveDirectory));
	p.addLast(ACK_RESPONSER, new AckResponser());
	p.addLast(ENCODER, new StringEncoder());
	p.remove(this);
}
 
Example #21
Source File: GraphiteClientPool.java    From gruffalo with Apache License 2.0 5 votes vote down vote up
private void initClients(final String[] hosts, final EventLoopGroup eventLoopGroup, final StringDecoder decoder, final StringEncoder encoder,
                         final Throttler throttler, final int inFlightBatchesHighThreshold, final MetricFactory metricFactory) {
  for (int i = 0; i < hosts.length; i++) {
    final String[] hostAndPort = hosts[i].split(":");
    final String host = hostAndPort[0];
    final int port = Integer.parseInt(hostAndPort[1]);

    final NettyGraphiteClient client = new NettyGraphiteClient(throttler, inFlightBatchesHighThreshold, metricFactory, hosts[i]);
    pool[i] = client;
    final ChannelHandler graphiteChannelHandler = new GraphiteChannelInboundHandler(client, hosts[i], throttler);
    final GraphiteClientChannelInitializer channelInitializer = new GraphiteClientChannelInitializer(host, port, eventLoopGroup, decoder, encoder,
        graphiteChannelHandler);
    client.setChannelInitializer(channelInitializer);
  }
}
 
Example #22
Source File: JumbuneAgentDecoder.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Invoke fire and forget command handler.
 *
 * @param ctx the ctx
 */
private void invokeFireAndForgetCommandHandler(ChannelHandlerContext ctx) {
	ChannelPipeline p = ctx.pipeline();
	p.addLast(DECODER, new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
	p.addLast("commandExecutor", new CommandDelegator());
	p.addLast(ENCODER, new StringEncoder());
	p.remove(this);
}
 
Example #23
Source File: LineBasedClient.java    From netty-learning with Apache License 2.0 5 votes vote down vote up
public void connect(String host, int port) throws InterruptedException {

		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group)
			.channel(NioSocketChannel.class)
			.option(ChannelOption.TCP_NODELAY, true)
			.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {

					ChannelPipeline p = ch.pipeline();
					p.addLast(new LineBasedFrameDecoder(1024));
					p.addLast(new StringDecoder());
					p.addLast(new StringEncoder());

					p.addLast(new LineClientHandler());
				}
			});

			ChannelFuture future = b.connect(Constants.HOST, Constants.PORT).sync();

			future.channel().closeFuture().sync();
		} finally {
			group.shutdownGracefully();
		}
	}
 
Example #24
Source File: NettyServer.java    From netty-learning with Apache License 2.0 5 votes vote down vote up
public void bind(int port) throws InterruptedException {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //配置服务器启动类
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 100)
                    .handler(new LoggingHandler(LogLevel.INFO))//配置日志输出
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch)
                                throws Exception {
                            ch.pipeline().addLast(new FixedLengthFrameDecoder(1<<5));
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new StringEncoder());

                            ch.pipeline().addLast(new ServerHandler());
                        }
                    });

            ChannelFuture f = b.bind(port).sync();
            //等待服务器退出
            f.channel().closeFuture().sync();
        } finally {
            //释放线程资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
 
Example #25
Source File: QosProcessHandler.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (in.readableBytes() < 1) {
        return;
    }

    // read one byte to guess protocol
    final int magic = in.getByte(in.readerIndex());

    ChannelPipeline p = ctx.pipeline();
    p.addLast(new LocalHostPermitHandler(acceptForeignIp));
    if (isHttp(magic)) {
        // no welcome output for http protocol
        if (welcomeFuture != null && welcomeFuture.isCancellable()) {
            welcomeFuture.cancel(false);
        }
        p.addLast(new HttpServerCodec());
        p.addLast(new HttpObjectAggregator(1048576));
        p.addLast(new HttpProcessHandler());
        p.remove(this);
    } else {
        p.addLast(new LineBasedFrameDecoder(2048));
        p.addLast(new StringDecoder(CharsetUtil.UTF_8));
        p.addLast(new StringEncoder(CharsetUtil.UTF_8));
        p.addLast(new IdleStateHandler(0, 0, 5 * 60));
        p.addLast(new TelnetProcessHandler());
        p.remove(this);
    }
}
 
Example #26
Source File: HelloServer.java    From netty-learning with Apache License 2.0 5 votes vote down vote up
public void run() throws Exception {

		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
			.channel(NioServerSocketChannel.class)
			.option(ChannelOption.SO_BACKLOG, 1024)
			.childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				public void initChannel(SocketChannel ch) throws Exception {

					ChannelPipeline p = ch.pipeline();
					p.addLast(new StringEncoder());
					p.addLast(new StringDecoder());
					p.addLast(new HelloServerHandler());
				}
			});

			// Bind and start to accept incoming connections.
			ChannelFuture f = b.bind(port).sync(); // (7)

			logger.info("server bind port:{}", port);

			// Wait until the server socket is closed.
			f.channel().closeFuture().sync();

		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
 
Example #27
Source File: GraphiteClientPool.java    From gruffalo with Apache License 2.0 5 votes vote down vote up
public GraphiteClientPool(final EventLoopGroup eventLoopGroup, final StringDecoder decoder,
                          final StringEncoder encoder, final Throttler throttler, final int inFlightBatchesHighThreshold, final MetricFactory metricFactory, final String graphiteRelayHosts) {
  Preconditions.checkNotNull(graphiteRelayHosts);
  Preconditions.checkNotNull(decoder, "decoder must not be null");
  Preconditions.checkNotNull(encoder, "encoder must not be null");
  Preconditions.checkNotNull(eventLoopGroup, "eventLoopGroup must not be null");

  logger.info("Creating a client pool for [{}]", graphiteRelayHosts);
  final String[] hosts = graphiteRelayHosts.trim().split(",");
  pool = new GraphiteClient[hosts.length];
  initClients(hosts, eventLoopGroup, decoder, encoder, throttler, inFlightBatchesHighThreshold, metricFactory);
}
 
Example #28
Source File: DelimiterClient.java    From netty-learning with Apache License 2.0 5 votes vote down vote up
public void connect(String host, int port) throws InterruptedException {

		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group)
			.channel(NioSocketChannel.class)
			.option(ChannelOption.TCP_NODELAY, true)
			.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {

					ChannelPipeline p = ch.pipeline();
					p.addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer(Constants.DELIMITER.getBytes())));
					p.addLast(new StringDecoder());
					p.addLast(new StringEncoder());

					p.addLast(new DelimiterClientHandler());
				}
			});

			ChannelFuture future = b.connect(Constants.HOST, Constants.PORT).sync();

			future.channel().closeFuture().sync();
		} finally {
			group.shutdownGracefully();
		}
	}
 
Example #29
Source File: ServerHandlersInit.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
protected void initChannel(SocketChannel socketChannel) throws Exception {

        SslHandler sslHandler = SSLHandlerProvider.getSSLHandler();

        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast(sslHandler);
        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        pipeline.addLast(new StringDecoder());
        pipeline.addLast(new StringEncoder());

        // and then business logic.
        pipeline.addLast(new SecureChatServerHandler());
    }
 
Example #30
Source File: HelloClient.java    From netty-learning with Apache License 2.0 5 votes vote down vote up
public void send() throws InterruptedException {

		EventLoopGroup group = new NioEventLoopGroup(10);

		try {
			Bootstrap b = new Bootstrap();
			b.group(group)
			.channel(NioSocketChannel.class)
			.option(ChannelOption.TCP_NODELAY, true)
			.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {

					ChannelPipeline p = ch.pipeline();
					p.addLast(new StringEncoder());
					p.addLast(new StringDecoder());
					p.addLast(new HelloClientHandler());
				}
			});

			ChannelFuture future = b.connect(Constants.HOST, Constants.PORT).sync();

			future.channel().closeFuture().sync();
		} finally {
			group.shutdownGracefully();
		}
	}