Search in sources :

Example 6 with SocketChannel

use of org.apache.flink.shaded.netty4.io.netty.channel.socket.SocketChannel in project pulsar by yahoo.

the class DiscoveryServiceTest method connectToService.

/**
     * creates ClientHandler channel to connect and communicate with server
     * 
     * @param serviceUrl
     * @param latch
     * @return
     * @throws URISyntaxException
     */
public static NioEventLoopGroup connectToService(String serviceUrl, CountDownLatch latch, boolean tls) throws URISyntaxException {
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            if (tls) {
                SslContextBuilder builder = SslContextBuilder.forClient();
                builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
                X509Certificate[] certificates = SecurityUtility.loadCertificatesFromPemFile(TLS_CLIENT_CERT_FILE_PATH);
                PrivateKey privateKey = SecurityUtility.loadPrivateKeyFromPemFile(TLS_CLIENT_KEY_FILE_PATH);
                builder.keyManager(privateKey, (X509Certificate[]) certificates);
                SslContext sslCtx = builder.build();
                ch.pipeline().addLast("tls", sslCtx.newHandler(ch.alloc()));
            }
            ch.pipeline().addLast(new ClientHandler(latch));
        }
    });
    URI uri = new URI(serviceUrl);
    InetSocketAddress serviceAddress = new InetSocketAddress(uri.getHost(), uri.getPort());
    b.connect(serviceAddress).addListener((ChannelFuture future) -> {
        if (!future.isSuccess()) {
            throw new IllegalStateException(future.cause());
        }
    });
    return workerGroup;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) PrivateKey(java.security.PrivateKey) InetSocketAddress(java.net.InetSocketAddress) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext)

Example 7 with SocketChannel

use of org.apache.flink.shaded.netty4.io.netty.channel.socket.SocketChannel in project cradle by BingLau7.

the class EchoClient method start.

void start() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        // 指定 EventLoopGroup 以处理客户端时间;需要适用于 NIO 的实现
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).remoteAddress(new InetSocketAddress(host, port)).handler(new ChannelInitializer<SocketChannel>() {

            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new EchoClientHandler());
            }
        });
        // 连接远程节点,阻塞等待直到连接完成
        ChannelFuture f = b.connect().sync();
        // 阻塞,直到 Channel 关闭
        f.channel().closeFuture().sync();
    } finally {
        // 关闭线程池并释放所有的资源
        group.shutdownGracefully().sync();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) InetSocketAddress(java.net.InetSocketAddress) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 8 with SocketChannel

use of org.apache.flink.shaded.netty4.io.netty.channel.socket.SocketChannel in project cradle by BingLau7.

the class EchoServer method start.

void start() throws Exception {
    // 创建 Event-LoopGroup
    NioEventLoopGroup group = new NioEventLoopGroup();
    try {
        // 创建 Server-Bootstrap
        ServerBootstrap b = new ServerBootstrap();
        b.group(group).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port)).childHandler(new ChannelInitializer<SocketChannel>() {

            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new EchoServerHandler());
            }
        });
        // 异步地绑定服务器;调用 sync() 方法阻塞等待直到绑定完成
        ChannelFuture f = b.bind().sync();
        System.out.println(EchoServer.class.getName() + " started and listen on " + f.channel().localAddress());
        // 获取 Channel 的 CloseFuture,并且阻塞当前线程直到它完成
        f.channel().closeFuture().sync();
    } finally {
        // 关闭 EventLoopGroup,释放所有的资源
        group.shutdownGracefully().sync();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 9 with SocketChannel

use of org.apache.flink.shaded.netty4.io.netty.channel.socket.SocketChannel in project cradle by BingLau7.

the class NettyNioServer method server.

public void server(int port) throws Exception {
    final ByteBuf buf = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("Hi!\r\n", Charset.forName("UTF-8")));
    // 为非阻塞模式使用 NioEventLoopGroup
    NioEventLoopGroup group = new NioEventLoopGroup();
    try {
        // 创建 ServerBootstrap
        ServerBootstrap b = new ServerBootstrap();
        b.group(group).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port)).childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                // 添加一个 ChannelInBoundHandlerAdapter 以拦截和处理事件
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        // 将消息写到客户端,并添加 ChannelFutureListener 以便消息已被写完就关闭连接
                        ctx.writeAndFlush(buf.duplicate()).addListener(ChannelFutureListener.CLOSE);
                    }
                });
            }
        });
        // 绑定服务器以接收连接
        ChannelFuture f = b.bind().sync();
        f.channel().closeFuture().sync();
    } finally {
        // 释放所有资源
        group.shutdownGracefully().sync();
    }
}
Also used : NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) ByteBuf(io.netty.buffer.ByteBuf) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 10 with SocketChannel

use of org.apache.flink.shaded.netty4.io.netty.channel.socket.SocketChannel in project pulsar by yahoo.

the class MockBrokerService method startMockBrokerService.

public void startMockBrokerService() throws Exception {
    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("mock-pulsar-%s").build();
    final int numThreads = 2;
    final int MaxMessageSize = 5 * 1024 * 1024;
    EventLoopGroup eventLoopGroup;
    try {
        if (SystemUtils.IS_OS_LINUX) {
            try {
                eventLoopGroup = new EpollEventLoopGroup(numThreads, threadFactory);
            } catch (UnsatisfiedLinkError e) {
                eventLoopGroup = new NioEventLoopGroup(numThreads, threadFactory);
            }
        } else {
            eventLoopGroup = new NioEventLoopGroup(numThreads, threadFactory);
        }
        workerGroup = eventLoopGroup;
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(workerGroup, workerGroup);
        if (workerGroup instanceof EpollEventLoopGroup) {
            bootstrap.channel(EpollServerSocketChannel.class);
        } else {
            bootstrap.channel(NioServerSocketChannel.class);
        }
        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(MaxMessageSize, 0, 4, 0, 4));
                ch.pipeline().addLast("handler", new MockServerCnx());
            }
        });
        // Bind and start to accept incoming connections.
        bootstrap.bind(brokerServicePort).sync();
    } catch (Exception e) {
        throw e;
    }
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Aggregations

SocketChannel (io.netty.channel.socket.SocketChannel)278 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)151 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)114 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)107 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)105 Bootstrap (io.netty.bootstrap.Bootstrap)103 ChannelPipeline (io.netty.channel.ChannelPipeline)94 ChannelFuture (io.netty.channel.ChannelFuture)93 EventLoopGroup (io.netty.channel.EventLoopGroup)92 InetSocketAddress (java.net.InetSocketAddress)46 LoggingHandler (io.netty.handler.logging.LoggingHandler)45 IOException (java.io.IOException)44 Channel (io.netty.channel.Channel)42 LengthFieldBasedFrameDecoder (io.netty.handler.codec.LengthFieldBasedFrameDecoder)36 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)35 SslContext (io.netty.handler.ssl.SslContext)34 ByteBuf (io.netty.buffer.ByteBuf)31 StringDecoder (io.netty.handler.codec.string.StringDecoder)27 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)19 LengthFieldPrepender (io.netty.handler.codec.LengthFieldPrepender)18