Search in sources :

Example 96 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project x-pipe by ctripcorp.

the class DefaultRedisKeeperServer method startServer.

protected void startServer() throws InterruptedException {
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(new LoggingHandler(LogLevel.DEBUG));
            p.addLast(new NettySimpleMessageHandler());
            p.addLast(new NettyMasterHandler(DefaultRedisKeeperServer.this, new CommandHandlerManager(), keeperConfig.getTrafficReportIntervalMillis()));
        }
    });
    serverSocketChannel = (ServerSocketChannel) b.bind(currentKeeperMeta.getPort()).sync().channel();
}
Also used : NettyMasterHandler(com.ctrip.xpipe.redis.keeper.netty.NettyMasterHandler) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) ServerSocketChannel(io.netty.channel.socket.ServerSocketChannel) LoggingHandler(io.netty.handler.logging.LoggingHandler) NettySimpleMessageHandler(com.ctrip.xpipe.netty.NettySimpleMessageHandler) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) XpipeRuntimeException(com.ctrip.xpipe.exception.XpipeRuntimeException) RedisSlavePromotionException(com.ctrip.xpipe.redis.keeper.exception.RedisSlavePromotionException) IOException(java.io.IOException) ChannelPipeline(io.netty.channel.ChannelPipeline) CommandHandlerManager(com.ctrip.xpipe.redis.keeper.handler.CommandHandlerManager)

Example 97 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project motan by weibocom.

the class NettyClient method open.

@Override
public synchronized boolean open() {
    if (isAvailable()) {
        return true;
    }
    bootstrap = new Bootstrap();
    int timeout = getUrl().getIntParameter(URLParamType.connectTimeout.getName(), URLParamType.connectTimeout.getIntValue());
    if (timeout <= 0) {
        throw new MotanFrameworkException("NettyClient init Error: timeout(" + timeout + ") <= 0 is forbid.", MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
    }
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    // 最大响应包限制
    final int maxContentLength = url.getIntParameter(URLParamType.maxContentLength.getName(), URLParamType.maxContentLength.getIntValue());
    bootstrap.group(nioEventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("decoder", new NettyDecoder(codec, NettyClient.this, maxContentLength));
            pipeline.addLast("encoder", new NettyEncoder());
            pipeline.addLast("handler", new NettyChannelHandler(NettyClient.this, new MessageHandler() {

                @Override
                public Object handle(Channel channel, Object message) {
                    Response response = (Response) message;
                    ResponseFuture responseFuture = NettyClient.this.removeCallback(response.getRequestId());
                    if (responseFuture == null) {
                        LoggerUtil.warn("NettyClient has response from server, but responseFuture not exist, requestId={}", response.getRequestId());
                        return null;
                    }
                    if (response.getException() != null) {
                        responseFuture.onFailure(response);
                    } else {
                        responseFuture.onSuccess(response);
                    }
                    return null;
                }
            }));
        }
    });
    // 初始化连接池
    initPool();
    LoggerUtil.info("NettyClient finish Open: url={}", url);
    // 注册统计回调
    StatsUtil.registryStatisticCallback(this);
    // 设置可用状态
    state = ChannelState.ALIVE;
    return true;
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) MotanServiceException(com.weibo.api.motan.exception.MotanServiceException) MotanAbstractException(com.weibo.api.motan.exception.MotanAbstractException) MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException) ChannelPipeline(io.netty.channel.ChannelPipeline) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap)

Example 98 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project motan by weibocom.

the class NettyServer method open.

@Override
public boolean open() {
    if (isAvailable()) {
        LoggerUtil.warn("NettyServer ServerChannel already Open: url=" + url);
        return state.isAliveState();
    }
    if (bossGroup == null) {
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
    }
    LoggerUtil.info("NettyServer ServerChannel start Open: url=" + url);
    boolean shareChannel = url.getBooleanParameter(URLParamType.shareChannel.getName(), URLParamType.shareChannel.getBooleanValue());
    final int maxContentLength = url.getIntParameter(URLParamType.maxContentLength.getName(), URLParamType.maxContentLength.getIntValue());
    int maxServerConnection = url.getIntParameter(URLParamType.maxServerConnection.getName(), URLParamType.maxServerConnection.getIntValue());
    int workerQueueSize = url.getIntParameter(URLParamType.workerQueueSize.getName(), URLParamType.workerQueueSize.getIntValue());
    int minWorkerThread, maxWorkerThread;
    if (shareChannel) {
        minWorkerThread = url.getIntParameter(URLParamType.minWorkerThread.getName(), MotanConstants.NETTY_SHARECHANNEL_MIN_WORKDER);
        maxWorkerThread = url.getIntParameter(URLParamType.maxWorkerThread.getName(), MotanConstants.NETTY_SHARECHANNEL_MAX_WORKDER);
    } else {
        minWorkerThread = url.getIntParameter(URLParamType.minWorkerThread.getName(), MotanConstants.NETTY_NOT_SHARECHANNEL_MIN_WORKDER);
        maxWorkerThread = url.getIntParameter(URLParamType.maxWorkerThread.getName(), MotanConstants.NETTY_NOT_SHARECHANNEL_MAX_WORKDER);
    }
    standardThreadExecutor = (standardThreadExecutor != null && !standardThreadExecutor.isShutdown()) ? standardThreadExecutor : new StandardThreadExecutor(minWorkerThread, maxWorkerThread, workerQueueSize, new DefaultThreadFactory("NettyServer-" + url.getServerPortStr(), true));
    standardThreadExecutor.prestartAllCoreThreads();
    channelManage = new NettyServerChannelManage(maxServerConnection);
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("channel_manage", channelManage);
            pipeline.addLast("decoder", new NettyDecoder(codec, NettyServer.this, maxContentLength));
            pipeline.addLast("encoder", new NettyEncoder());
            NettyChannelHandler handler = new NettyChannelHandler(NettyServer.this, messageHandler, standardThreadExecutor);
            pipeline.addLast("handler", handler);
        }
    });
    serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress(url.getPort()));
    channelFuture.syncUninterruptibly();
    serverChannel = channelFuture.channel();
    setLocalAddress((InetSocketAddress) serverChannel.localAddress());
    if (url.getPort() == 0) {
        url.setPort(getLocalAddress().getPort());
    }
    state = ChannelState.ALIVE;
    StatsUtil.registryStatisticCallback(this);
    LoggerUtil.info("NettyServer ServerChannel finish Open: url=" + url);
    return state.isAliveState();
}
Also used : NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) StandardThreadExecutor(com.weibo.api.motan.core.StandardThreadExecutor) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) MotanFrameworkException(com.weibo.api.motan.exception.MotanFrameworkException) TransportException(com.weibo.api.motan.transport.TransportException) DefaultThreadFactory(com.weibo.api.motan.core.DefaultThreadFactory) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 99 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project zipkin by openzipkin.

the class NettyScribeServer method start.

void start() {
    bossGroup = EventLoopGroups.newEventLoopGroup(1);
    EventLoopGroup workerGroup = CommonPools.workerGroup();
    ServerBootstrap b = new ServerBootstrap();
    try {
        channel = b.group(bossGroup, workerGroup).channel(EventLoopGroups.serverChannelType(bossGroup)).childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) {
                ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4)).addLast(new ScribeInboundHandler(scribe));
            }
        }).bind(port).syncUninterruptibly().channel();
    } catch (Throwable t) {
        propagateIfFatal(t);
        throw new RuntimeException("Could not start scribe server.", t);
    }
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) EventLoopGroup(io.netty.channel.EventLoopGroup) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 100 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project flink by apache.

the class NettyClient method connect.

// ------------------------------------------------------------------------
// Client connections
// ------------------------------------------------------------------------
ChannelFuture connect(final InetSocketAddress serverSocketAddress) {
    checkState(bootstrap != null, "Client has not been initialized yet.");
    // --------------------------------------------------------------------
    // Child channel pipeline for accepted connections
    // --------------------------------------------------------------------
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel channel) throws Exception {
            // SSL handler should be added first in the pipeline
            if (clientSSLFactory != null) {
                SslHandler sslHandler = clientSSLFactory.createNettySSLHandler(channel.alloc(), serverSocketAddress.getAddress().getCanonicalHostName(), serverSocketAddress.getPort());
                channel.pipeline().addLast("ssl", sslHandler);
            }
            channel.pipeline().addLast(protocol.getClientChannelHandlers());
        }
    });
    try {
        return bootstrap.connect(serverSocketAddress);
    } catch (ChannelException e) {
        if ((e.getCause() instanceof java.net.SocketException && e.getCause().getMessage().equals("Too many open files")) || (e.getCause() instanceof ChannelException && e.getCause().getCause() instanceof java.net.SocketException && e.getCause().getCause().getMessage().equals("Too many open files"))) {
            throw new ChannelException("The operating system does not offer enough file handles to open the network connection. " + "Please increase the number of available file handles.", e.getCause());
        } else {
            throw e;
        }
    }
}
Also used : EpollSocketChannel(org.apache.flink.shaded.netty4.io.netty.channel.epoll.EpollSocketChannel) NioSocketChannel(org.apache.flink.shaded.netty4.io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(org.apache.flink.shaded.netty4.io.netty.channel.socket.SocketChannel) IOException(java.io.IOException) ChannelException(org.apache.flink.shaded.netty4.io.netty.channel.ChannelException) SslHandler(org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslHandler) ChannelException(org.apache.flink.shaded.netty4.io.netty.channel.ChannelException)

Aggregations

SocketChannel (io.netty.channel.socket.SocketChannel)235 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)137 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)101 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)94 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)94 Bootstrap (io.netty.bootstrap.Bootstrap)89 ChannelPipeline (io.netty.channel.ChannelPipeline)79 EventLoopGroup (io.netty.channel.EventLoopGroup)79 ChannelFuture (io.netty.channel.ChannelFuture)77 InetSocketAddress (java.net.InetSocketAddress)43 LoggingHandler (io.netty.handler.logging.LoggingHandler)42 Channel (io.netty.channel.Channel)35 IOException (java.io.IOException)33 SslContext (io.netty.handler.ssl.SslContext)30 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)29 LengthFieldBasedFrameDecoder (io.netty.handler.codec.LengthFieldBasedFrameDecoder)29 ByteBuf (io.netty.buffer.ByteBuf)27 StringDecoder (io.netty.handler.codec.string.StringDecoder)23 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)18 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)15