Search in sources :

Example 31 with Bootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.Bootstrap in project camel by apache.

the class SingleUDPNettyServerBootstrapFactory method startServerBootstrap.

protected void startServerBootstrap() throws Exception {
    // create non-shared worker pool
    EventLoopGroup wg = configuration.getWorkerGroup();
    if (wg == null) {
        // create new pool which we should shutdown when stopping as its not shared
        workerGroup = new NettyWorkerPoolBuilder().withNativeTransport(configuration.isNativeTransport()).withWorkerCount(configuration.getWorkerCount()).withName("NettyServerTCPWorker").build();
        wg = workerGroup;
    }
    Bootstrap bootstrap = new Bootstrap();
    if (configuration.isNativeTransport()) {
        bootstrap.group(wg).channel(EpollDatagramChannel.class);
    } else {
        bootstrap.group(wg).channel(NioDatagramChannel.class);
    }
    // We cannot set the child option here      
    bootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
    bootstrap.option(ChannelOption.SO_SNDBUF, configuration.getSendBufferSize());
    bootstrap.option(ChannelOption.SO_RCVBUF, configuration.getReceiveBufferSize());
    bootstrap.option(ChannelOption.SO_BROADCAST, configuration.isBroadcast());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());
    // only set this if user has specified
    if (configuration.getReceiveBufferSizePredictor() > 0) {
        bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(configuration.getReceiveBufferSizePredictor()));
    }
    if (configuration.getBacklog() > 0) {
        bootstrap.option(ChannelOption.SO_BACKLOG, configuration.getBacklog());
    }
    Map<String, Object> options = configuration.getOptions();
    if (options != null) {
        for (Map.Entry<String, Object> entry : options.entrySet()) {
            String value = entry.getValue().toString();
            ChannelOption<Object> option = ChannelOption.valueOf(entry.getKey());
            //TODO: find a way to add primitive Netty options without having to add them to the Camel registry.
            if (EndpointHelper.isReferenceParameter(value)) {
                String name = value.substring(1);
                Object o = CamelContextHelper.mandatoryLookup(camelContext, name);
                bootstrap.option(option, o);
            } else {
                bootstrap.option(option, value);
            }
        }
    }
    LOG.debug("Created Bootstrap {}", bootstrap);
    // set the pipeline factory, which creates the pipeline for each newly created channels
    bootstrap.handler(pipelineFactory);
    InetSocketAddress hostAddress = new InetSocketAddress(configuration.getHost(), configuration.getPort());
    SubnetUtils multicastSubnet = new SubnetUtils(MULTICAST_SUBNET);
    if (multicastSubnet.getInfo().isInRange(configuration.getHost())) {
        ChannelFuture channelFuture = bootstrap.bind(configuration.getPort()).sync();
        channel = channelFuture.channel();
        DatagramChannel datagramChannel = (DatagramChannel) channel;
        String networkInterface = configuration.getNetworkInterface() == null ? LOOPBACK_INTERFACE : configuration.getNetworkInterface();
        multicastNetworkInterface = NetworkInterface.getByName(networkInterface);
        ObjectHelper.notNull(multicastNetworkInterface, "No network interface found for '" + networkInterface + "'.");
        LOG.info("ConnectionlessBootstrap joining {}:{} using network interface: {}", new Object[] { configuration.getHost(), configuration.getPort(), multicastNetworkInterface.getName() });
        datagramChannel.joinGroup(hostAddress, multicastNetworkInterface).syncUninterruptibly();
        allChannels.add(datagramChannel);
    } else {
        LOG.info("ConnectionlessBootstrap binding to {}:{}", configuration.getHost(), configuration.getPort());
        ChannelFuture channelFuture = bootstrap.bind(hostAddress).sync();
        channel = channelFuture.channel();
        allChannels.add(channel);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SubnetUtils(org.apache.camel.component.netty4.util.SubnetUtils) InetSocketAddress(java.net.InetSocketAddress) EpollDatagramChannel(io.netty.channel.epoll.EpollDatagramChannel) DatagramChannel(io.netty.channel.socket.DatagramChannel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) EventLoopGroup(io.netty.channel.EventLoopGroup) FixedRecvByteBufAllocator(io.netty.channel.FixedRecvByteBufAllocator) Bootstrap(io.netty.bootstrap.Bootstrap) Map(java.util.Map)

Example 32 with Bootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.Bootstrap in project camel by apache.

the class NettyUDPByteArrayProviderTest method createNettyUdpReceiver.

public void createNettyUdpReceiver() {
    group = new NioEventLoopGroup();
    bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioDatagramChannel.class).handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel channel) throws Exception {
            channel.pipeline().addLast(new UdpHandler());
            channel.pipeline().addLast(new ByteArrayDecoder());
            channel.pipeline().addLast(new ContentHandler());
        }
    }).localAddress(new InetSocketAddress(getPort()));
}
Also used : InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ByteArrayDecoder(io.netty.handler.codec.bytes.ByteArrayDecoder)

Example 33 with Bootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.Bootstrap in project camel by apache.

the class NettyUdpConnectedSendTest method createNettyUdpReceiver.

public void createNettyUdpReceiver() {
    group = new NioEventLoopGroup();
    bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioDatagramChannel.class).handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel channel) throws Exception {
            channel.pipeline().addLast(new UdpHandler());
            channel.pipeline().addLast(new ContentHandler());
        }
    }).localAddress(new InetSocketAddress(getPort()));
}
Also used : InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 34 with Bootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.Bootstrap in project proxyee-down by monkeyWie.

the class AbstractHttpDownBootstrap method startChunkDown.

protected void startChunkDown(ChunkInfo chunkInfo, int updateStatus) throws Exception {
    HttpRequestInfo requestInfo = (HttpRequestInfo) httpDownInfo.getRequest();
    RequestProto requestProto = requestInfo.requestProto();
    LOGGER.debug("开始下载:" + chunkInfo);
    Bootstrap bootstrap = new Bootstrap().channel(NioSocketChannel.class).group(clientLoopGroup).handler(new HttpDownInitializer(requestProto.getSsl(), this, chunkInfo));
    if (httpDownInfo.getProxyConfig() != null) {
        // 代理服务器解析DNS和连接
        bootstrap.resolver(NoopAddressResolverGroup.INSTANCE);
    }
    if (callback != null) {
        callback.onChunkConnecting(httpDownInfo, chunkInfo);
    }
    ChannelFuture cf = bootstrap.connect(requestProto.getHost(), requestProto.getPort());
    chunkInfo.setStatus(updateStatus);
    // 重置最后下载时间
    chunkInfo.setLastDownTime(System.currentTimeMillis());
    cf.addListener((ChannelFutureListener) future -> {
        if (future.isSuccess()) {
            synchronized (chunkInfo) {
                setChannel(chunkInfo, future.channel());
            }
            synchronized (requestInfo) {
                LOGGER.debug("下载连接成功:channelId[" + future.channel().id() + "]\t" + chunkInfo);
                if (httpDownInfo.getTaskInfo().isSupportRange()) {
                    requestInfo.headers().set(HttpHeaderNames.RANGE, "bytes=" + chunkInfo.getNowStartPosition() + "-" + chunkInfo.getEndPosition());
                } else {
                    requestInfo.headers().remove(HttpHeaderNames.RANGE);
                }
                future.channel().writeAndFlush(httpDownInfo.getRequest());
            }
            if (requestInfo.content() != null) {
                HttpContent content = new DefaultLastHttpContent();
                content.content().writeBytes(requestInfo.content());
                future.channel().writeAndFlush(content);
            }
        } else {
            LOGGER.debug("下载连接失败:" + chunkInfo);
            chunkInfo.setStatus(HttpDownStatus.FAIL);
            future.channel().close();
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) RandomAccessFile(java.io.RandomAccessFile) HttpDownStatus(lee.study.down.constant.HttpDownStatus) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) RequestProto(lee.study.proxyee.util.ProtoUtil.RequestProto) ByteBuffer(java.nio.ByteBuffer) FileUtil(lee.study.down.util.FileUtil) NoopAddressResolverGroup(io.netty.resolver.NoopAddressResolverGroup) TaskInfo(lee.study.down.model.TaskInfo) HttpDownInitializer(lee.study.down.handle.HttpDownInitializer) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Map(java.util.Map) ChunkInfo(lee.study.down.model.ChunkInfo) HttpContent(io.netty.handler.codec.http.HttpContent) Logger(org.slf4j.Logger) SslContext(io.netty.handler.ssl.SslContext) HttpRequestInfo(lee.study.down.model.HttpRequestInfo) IOException(java.io.IOException) HttpDownCallback(lee.study.down.dispatch.HttpDownCallback) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) File(java.io.File) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) Bootstrap(io.netty.bootstrap.Bootstrap) HttpDownInfo(lee.study.down.model.HttpDownInfo) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Closeable(java.io.Closeable) Data(lombok.Data) BootstrapException(lee.study.down.exception.BootstrapException) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) AllArgsConstructor(lombok.AllArgsConstructor) HttpDownUtil(lee.study.down.util.HttpDownUtil) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Bootstrap(io.netty.bootstrap.Bootstrap) HttpRequestInfo(lee.study.down.model.HttpRequestInfo) RequestProto(lee.study.proxyee.util.ProtoUtil.RequestProto) HttpDownInitializer(lee.study.down.handle.HttpDownInitializer) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent)

Example 35 with Bootstrap

use of org.apache.flink.shaded.netty4.io.netty.bootstrap.Bootstrap in project java-in-action by xinghalo.

the class EchoClient method start.

public void start() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).remoteAddress(new InetSocketAddress(host, port)).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new EchoClientHandler());
            }
        });
        ChannelFuture f = b.connect().sync();
        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)

Aggregations

Bootstrap (io.netty.bootstrap.Bootstrap)435 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)209 Channel (io.netty.channel.Channel)197 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)191 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)171 ChannelFuture (io.netty.channel.ChannelFuture)152 EventLoopGroup (io.netty.channel.EventLoopGroup)141 SocketChannel (io.netty.channel.socket.SocketChannel)125 InetSocketAddress (java.net.InetSocketAddress)121 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)117 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)109 Test (org.junit.jupiter.api.Test)89 ChannelPipeline (io.netty.channel.ChannelPipeline)76 LocalChannel (io.netty.channel.local.LocalChannel)74 LocalServerChannel (io.netty.channel.local.LocalServerChannel)71 LocalAddress (io.netty.channel.local.LocalAddress)66 CountDownLatch (java.util.concurrent.CountDownLatch)62 IOException (java.io.IOException)60 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)57 ChannelInitializer (io.netty.channel.ChannelInitializer)46