Search in sources :

Example 51 with NioEventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoopGroup in project dubbo by alibaba.

the class NettyServer method doOpen.

@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ServerBootstrap();
    bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true));
    workerGroup = new NioEventLoopGroup(getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS), new DefaultThreadFactory("NettyServerWorker", true));
    final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this);
    channels = nettyServerHandler.getChannels();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE).childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE).childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).childHandler(new ChannelInitializer<NioSocketChannel>() {

        @Override
        protected void initChannel(NioSocketChannel ch) throws Exception {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);
            // .addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
            ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("encoder", adapter.getEncoder()).addLast("handler", nettyServerHandler);
        }
    });
    // bind
    ChannelFuture channelFuture = bootstrap.bind(getBindAddress());
    channelFuture.syncUninterruptibly();
    channel = channelFuture.channel();
}
Also used : DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ChannelFuture(io.netty.channel.ChannelFuture) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) RemotingException(com.alibaba.dubbo.remoting.RemotingException)

Example 52 with NioEventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoopGroup in project geode by apache.

the class GeodeRedisServer method startRedisServer.

/**
   * Helper method to start the server listening for connections. The server is bound to the port
   * specified by {@link GeodeRedisServer#serverPort}
   * 
   * @throws IOException
   * @throws InterruptedException
   */
private void startRedisServer() throws IOException, InterruptedException {
    ThreadFactory selectorThreadFactory = new ThreadFactory() {

        private final AtomicInteger counter = new AtomicInteger();

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("GeodeRedisServer-SelectorThread-" + counter.incrementAndGet());
            t.setDaemon(true);
            return t;
        }
    };
    ThreadFactory workerThreadFactory = new ThreadFactory() {

        private final AtomicInteger counter = new AtomicInteger();

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("GeodeRedisServer-WorkerThread-" + counter.incrementAndGet());
            return t;
        }
    };
    bossGroup = null;
    workerGroup = null;
    Class<? extends ServerChannel> socketClass = null;
    if (singleThreadPerConnection) {
        bossGroup = new OioEventLoopGroup(Integer.MAX_VALUE, selectorThreadFactory);
        workerGroup = new OioEventLoopGroup(Integer.MAX_VALUE, workerThreadFactory);
        socketClass = OioServerSocketChannel.class;
    } else {
        bossGroup = new NioEventLoopGroup(this.numSelectorThreads, selectorThreadFactory);
        workerGroup = new NioEventLoopGroup(this.numWorkerThreads, workerThreadFactory);
        socketClass = NioServerSocketChannel.class;
    }
    InternalDistributedSystem system = (InternalDistributedSystem) cache.getDistributedSystem();
    String pwd = system.getConfig().getRedisPassword();
    final byte[] pwdB = Coder.stringToBytes(pwd);
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(socketClass).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            if (logger.fineEnabled())
                logger.fine("GeodeRedisServer-Connection established with " + ch.remoteAddress());
            ChannelPipeline p = ch.pipeline();
            p.addLast(ByteToCommandDecoder.class.getSimpleName(), new ByteToCommandDecoder());
            p.addLast(ExecutionHandlerContext.class.getSimpleName(), new ExecutionHandlerContext(ch, cache, regionCache, GeodeRedisServer.this, pwdB));
        }
    }).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_RCVBUF, getBufferSize()).childOption(ChannelOption.SO_KEEPALIVE, true).childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, GeodeRedisServer.connectTimeoutMillis).childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    // Bind and start to accept incoming connections.
    ChannelFuture f = b.bind(new InetSocketAddress(getBindAddress(), serverPort)).sync();
    if (this.logger.infoEnabled()) {
        String logMessage = "GeodeRedisServer started {" + getBindAddress() + ":" + serverPort + "}, Selector threads: " + this.numSelectorThreads;
        if (this.singleThreadPerConnection)
            logMessage += ", One worker thread per connection";
        else
            logMessage += ", Worker threads: " + this.numWorkerThreads;
        this.logger.info(logMessage);
    }
    this.serverChannel = f.channel();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ThreadFactory(java.util.concurrent.ThreadFactory) OioServerSocketChannel(io.netty.channel.socket.oio.OioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) OioEventLoopGroup(io.netty.channel.oio.OioEventLoopGroup) ByteToCommandDecoder(org.apache.geode.redis.internal.ByteToCommandDecoder) InetSocketAddress(java.net.InetSocketAddress) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutionHandlerContext(org.apache.geode.redis.internal.ExecutionHandlerContext) InternalDistributedSystem(org.apache.geode.distributed.internal.InternalDistributedSystem) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 53 with NioEventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoopGroup 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();
}
Also used : EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) LoggingHandler(io.netty.handler.logging.LoggingHandler) SSLEngine(javax.net.ssl.SSLEngine) SSLException(javax.net.ssl.SSLException) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) SSLException(javax.net.ssl.SSLException) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SSLParameters(javax.net.ssl.SSLParameters) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) File(java.io.File) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext) Before(org.junit.Before)

Example 54 with NioEventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoopGroup in project web3sdk by FISCO-BCOS.

the class ChannelConnections method startListen.

public void startListen(Integer port) {
    if (running) {
        logger.debug("服务已启动");
        return;
    }
    logger.debug("初始化connections listen");
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    final ChannelConnections selfService = this;
    final ThreadPoolTaskExecutor selfThreadPool = threadPool;
    try {
        serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                KeyStore ks = KeyStore.getInstance("JKS");
                ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
                Resource keystoreResource = resolver.getResource(getClientKeystorePath());
                Resource caResource = resolver.getResource(getCaCertPath());
                ks.load(keystoreResource.getInputStream(), getKeystorePassWord().toCharArray());
                /*
                	 * 每次连接使用新的handler
                	 * 连接信息从socketChannel中获取
                	 */
                ChannelHandler handler = new ChannelHandler();
                handler.setConnections(selfService);
                handler.setIsServer(true);
                handler.setThreadPool(selfThreadPool);
                SslContext sslCtx = SslContextBuilder.forServer((PrivateKey) ks.getKey("client", getClientCertPassWord().toCharArray()), (X509Certificate) ks.getCertificate("client")).trustManager(caResource.getFile()).build();
                ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()), new LengthFieldBasedFrameDecoder(1024 * 1024 * 4, 0, 4, -4, 0), new IdleStateHandler(idleTimeout, idleTimeout, idleTimeout, TimeUnit.MILLISECONDS), handler);
            }
        });
        ChannelFuture future = serverBootstrap.bind(port);
        future.get();
        running = true;
    } catch (Exception e) {
        logger.error("系统错误", e);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) LoggingHandler(io.netty.handler.logging.LoggingHandler) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) PathMatchingResourcePatternResolver(org.springframework.core.io.support.PathMatchingResourcePatternResolver) ResourcePatternResolver(org.springframework.core.io.support.ResourcePatternResolver) PrivateKey(java.security.PrivateKey) Resource(org.springframework.core.io.Resource) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) ThreadPoolTaskExecutor(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor) PathMatchingResourcePatternResolver(org.springframework.core.io.support.PathMatchingResourcePatternResolver) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext)

Example 55 with NioEventLoopGroup

use of org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoopGroup 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();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) SocketChannel(io.netty.channel.socket.SocketChannel) StringDecoder(io.netty.handler.codec.string.StringDecoder) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) ChannelPipeline(io.netty.channel.ChannelPipeline) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) StringEncoder(io.netty.handler.codec.string.StringEncoder) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Aggregations

NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)521 EventLoopGroup (io.netty.channel.EventLoopGroup)256 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)226 Bootstrap (io.netty.bootstrap.Bootstrap)184 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)178 SocketChannel (io.netty.channel.socket.SocketChannel)169 ChannelFuture (io.netty.channel.ChannelFuture)157 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)157 Channel (io.netty.channel.Channel)138 InetSocketAddress (java.net.InetSocketAddress)118 LoggingHandler (io.netty.handler.logging.LoggingHandler)87 ChannelPipeline (io.netty.channel.ChannelPipeline)84 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)73 SslContext (io.netty.handler.ssl.SslContext)64 SelfSignedCertificate (io.netty.handler.ssl.util.SelfSignedCertificate)49 IOException (java.io.IOException)49 EpollEventLoopGroup (io.netty.channel.epoll.EpollEventLoopGroup)47 ByteBuf (io.netty.buffer.ByteBuf)44 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)43 ChannelInitializer (io.netty.channel.ChannelInitializer)41