use of io.netty.channel.ChannelPipeline in project pravega by pravega.
the class ConnectionFactoryImpl method establishConnection.
@Override
public CompletableFuture<ClientConnection> establishConnection(PravegaNodeUri location, ReplyProcessor rp) {
Preconditions.checkNotNull(location);
Exceptions.checkNotClosed(closed.get(), this);
final SslContext sslCtx;
if (clientConfig.isEnableTls()) {
try {
SslContextBuilder sslCtxFactory = SslContextBuilder.forClient();
if (Strings.isNullOrEmpty(clientConfig.getTrustStore())) {
sslCtxFactory = sslCtxFactory.trustManager(FingerprintTrustManagerFactory.getInstance(FingerprintTrustManagerFactory.getDefaultAlgorithm()));
} else {
sslCtxFactory = SslContextBuilder.forClient().trustManager(new File(clientConfig.getTrustStore()));
}
sslCtx = sslCtxFactory.build();
} catch (SSLException | NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
} else {
sslCtx = null;
}
AppendBatchSizeTracker batchSizeTracker = new AppendBatchSizeTrackerImpl();
ClientConnectionInboundHandler handler = new ClientConnectionInboundHandler(location.getEndpoint(), rp, batchSizeTracker);
Bootstrap b = new Bootstrap();
b.group(group).channel(nio ? NioSocketChannel.class : EpollSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
SslHandler sslHandler = sslCtx.newHandler(ch.alloc(), location.getEndpoint(), location.getPort());
if (clientConfig.isValidateHostName()) {
SSLEngine sslEngine = sslHandler.engine();
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
sslEngine.setSSLParameters(sslParameters);
}
p.addLast(sslHandler);
}
// p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(new ExceptionLoggingHandler(location.getEndpoint()), new CommandEncoder(batchSizeTracker), new LengthFieldBasedFrameDecoder(WireCommands.MAX_WIRECOMMAND_SIZE, 4, 4), new CommandDecoder(), handler);
}
});
// Start the client.
CompletableFuture<ClientConnection> connectionComplete = new CompletableFuture<>();
try {
b.connect(location.getEndpoint(), location.getPort()).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
if (future.isSuccess()) {
// since ChannelFuture is complete future.channel() is not a blocking call.
Channel ch = future.channel();
log.debug("Connect operation completed for channel:{}, local address:{}, remote address:{}", ch.id(), ch.localAddress(), ch.remoteAddress());
// Once a channel is closed the channel group implementation removes it.
allChannels.add(ch);
connectionComplete.complete(handler);
} else {
connectionComplete.completeExceptionally(new ConnectionFailedException(future.cause()));
}
}
});
} catch (Exception e) {
connectionComplete.completeExceptionally(new ConnectionFailedException(e));
}
// check if channel is registered.
CompletableFuture<Void> channelRegisteredFuture = new CompletableFuture<>();
handler.completeWhenRegistered(channelRegisteredFuture);
return connectionComplete.thenCombine(channelRegisteredFuture, (clientConnection, v) -> clientConnection);
}
use of io.netty.channel.ChannelPipeline in project pravega by pravega.
the class ConnectionFactoryImplTest method setUp.
@Before
public void setUp() throws Exception {
// Configure SSL.
port = TestUtils.getAvailableListenPort();
final SslContext sslCtx;
if (ssl) {
try {
sslCtx = SslContextBuilder.forServer(new File("../config/cert.pem"), new File("../config/key.pem")).build();
} catch (SSLException e) {
throw new RuntimeException(e);
}
} else {
sslCtx = null;
}
boolean nio = false;
EventLoopGroup bossGroup;
EventLoopGroup workerGroup;
try {
bossGroup = new EpollEventLoopGroup(1);
workerGroup = new EpollEventLoopGroup();
} catch (ExceptionInInitializerError | UnsatisfiedLinkError | NoClassDefFoundError e) {
nio = true;
bossGroup = new NioEventLoopGroup(1);
workerGroup = new NioEventLoopGroup();
}
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(nio ? NioServerSocketChannel.class : EpollServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
SslHandler handler = sslCtx.newHandler(ch.alloc());
SSLEngine sslEngine = handler.engine();
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("LDAPS");
sslEngine.setSSLParameters(sslParameters);
p.addLast(handler);
}
}
});
// Start the server.
serverChannel = b.bind("localhost", port).awaitUninterruptibly().channel();
}
use of io.netty.channel.ChannelPipeline in project transporter by wang4ever.
the class WSChildHandlerInitializer method initChannel.
@Override
public void initChannel(SocketChannel ch) throws Exception {
WSConfig conf = this.config.getWsConfig();
if (logger.isDebugEnabled())
logger.debug("Initital channel handler...\twebsocketPath={}", conf.getWebsocketPath());
ChannelPipeline p = ch.pipeline();
// Configure SSL.
if (conf.getSslEnable()) {
/*
* SelfSignedCertificate ssc = new SelfSignedCertificate();
* SslContext sslCtx =
* SslContextBuilder.forServer(ssc.certificate(),
* ssc.privateKey()).build();
*/
File keyCertChainFile = new File(Resources.getResource(conf.getKeyCertChainFile()).getFile());
File keyFile = new File(Resources.getResource(conf.getKeyFile()).getFile());
SslContext sslCtx = SslContextBuilder.forServer(keyCertChainFile, keyFile).build();
p.addLast(sslCtx.newHandler(ch.alloc()));
if (logger.isDebugEnabled())
logger.debug("The ssl(wss) handler has been enabled. sslCtx={}", sslCtx.toString());
}
// pipeline管理channel中的Handler,在channel队列中添加一个handler来处理业务
if (conf.getLoggingEnable()) {
p.addLast(new LoggingHandler(LogLevel.valueOf(conf.getLoggingLevel())));
if (logger.isInfoEnabled())
logger.info("Netty internal log has been used. (WS)level={}", conf.getLoggingLevel());
}
IdleStateHandler idleHandler = new IdleStateHandler(conf.getReadIdleSeconds(), conf.getWriteIdleSeconds(), conf.getAllIdleSeconds());
p.addLast(idleHandler);
// 将请求和应答消息解码为HTTP消息
p.addLast("http-codec", new HttpServerCodec());
// 将HTTP消息的多个部分合成一条完整的HTTP消息
p.addLast("aggregator", new HttpObjectAggregator(65536));
// 向客户端发送HTML5文件
p.addLast("http-chunked", new ChunkedWriteHandler());
p.addLast("ws-protocol", new WebSocketServerProtocolHandler(conf.getWebsocketPath(), null, true));
p.addLast("text-handler", SpringContextHolder.getBean("textWSFrameHandler"));
}
use of io.netty.channel.ChannelPipeline in project baseio by generallycloud.
the class NettyClientThread method main.
public static void main(String[] args) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group);
b.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
b.handler(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 StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast("handler", new HelloClient());
}
});
System.out.println("################## Test start ####################");
ChannelFuture f = b.connect("127.0.0.1", 5656).sync();
System.out.println(f.isSuccess());
Channel channel = f.channel();
System.out.println("channel is active :" + channel.isActive() + ",channel:" + channel);
int len = 1024 * 64;
StringBuilder s = new StringBuilder(len);
for (int i = 0; i < len; i++) {
s.append(len % 10);
}
final String msg = s.toString();
ThreadUtil.execute(new Runnable() {
@Override
public void run() {
int i = 0;
for (; ; ) {
// String s = "hello Service! ---> :" + i;
ChannelFuture f = channel.writeAndFlush(msg);
ThreadUtil.sleep(1);
System.out.println(f.isDone() + "--------" + i);
i++;
}
}
});
ThreadUtil.sleep(Integer.MAX_VALUE);
f.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
}
use of io.netty.channel.ChannelPipeline in project baseio by generallycloud.
the class TestLoadEchoClient1 method prepare.
@Override
public void prepare() throws Exception {
eventHandleAdaptor = new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
// System.out.println("_________________"+msg);
// ctx.write(msg);
addCount(1);
}
};
Bootstrap b = new Bootstrap();
b.group(group);
b.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, false);
b.handler(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 StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast("handler", eventHandleAdaptor);
}
});
f = b.connect("localhost", 5656).sync();
}
Aggregations