Example usage for io.netty.channel.socket DatagramChannel pipeline

List of usage examples for io.netty.channel.socket DatagramChannel pipeline

Introduction

In this page you can find the example usage for io.netty.channel.socket DatagramChannel pipeline.

Prototype

ChannelPipeline pipeline();

Source Link

Document

Return the assigned ChannelPipeline .

Usage

From source file:c5db.discovery.BeaconService.java

License:Apache License

@Override
protected void doStart() {
    eventLoopGroup.next().execute(() -> {
        bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup).channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, true)
                .handler(new ChannelInitializer<DatagramChannel>() {
                    @Override/*from   www. j a v  a  2  s .  c  om*/
                    protected void initChannel(DatagramChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();

                        p.addLast("protobufDecoder",
                                new UdpProtostuffDecoder<>(Availability.getSchema(), false));

                        p.addLast("protobufEncoder",
                                new UdpProtostuffEncoder<>(Availability.getSchema(), false));

                        p.addLast("beaconMessageHandler", new BeaconMessageHandler());
                    }
                });
        // Wait, this is why we are in a new executor...
        //noinspection RedundantCast
        bootstrap.bind(discoveryPort).addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                broadcastChannel = future.channel();
            } else {
                LOG.error("Unable to bind! ", future.cause());
                notifyFailed(future.cause());
            }
        });

        try {
            localIPs = getLocalIPs();
        } catch (SocketException e) {
            LOG.error("SocketException:", e);
            notifyFailed(e);
            return;
        }

        fiber = fiberSupplier.getNewFiber(this::notifyFailed);
        fiber.start();

        // Schedule fiber tasks and subscriptions.
        incomingMessages.subscribe(fiber, this::processWireMessage);
        nodeInfoRequests.subscribe(fiber, this::handleNodeInfoRequest);
        moduleInformationProvider.moduleChangeChannel().subscribe(fiber, this::updateCurrentModulePorts);

        if (localIPs.isEmpty()) {
            LOG.warn(
                    "Found no IP addresses to broadcast to other nodes; as a result, only sending to loopback");
        }

        fiber.scheduleAtFixedRate(this::sendBeacon, BEACON_SERVICE_INITIAL_BROADCAST_DELAY_MILLISECONDS,
                BEACON_SERVICE_BROADCAST_PERIOD_MILLISECONDS, TimeUnit.MILLISECONDS);

        C5Futures.addCallback(moduleInformationProvider.getOnlineModules(),
                (ImmutableMap<ModuleType, Integer> onlineModuleToPortMap) -> {
                    updateCurrentModulePorts(onlineModuleToPortMap);
                    notifyStarted();
                }, this::notifyFailed, fiber);
    });
}

From source file:c5db.eventLogging.EventLogListener.java

License:Apache License

@Override
protected void doStart() {
    nioEventLoopGroup.next().execute(() -> {

        Bootstrap bootstrap = new Bootstrap();
        try {//from  w w  w .  j a  v  a 2s  . co m
            bootstrap.group(nioEventLoopGroup).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, true)
                    .handler(new ChannelInitializer<DatagramChannel>() {
                        @Override
                        protected void initChannel(DatagramChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast("protostuffDecoder",
                                    new UdpProtostuffDecoder<>(EventLogEntry.getSchema(), false));
                            p.addLast("logger", new MsgHandler());
                        }
                    });

            bootstrap.bind(port).addListener(new GenericFutureListener<ChannelFuture>() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    channel = future.channel();
                }
            });

            notifyStarted();
        } catch (Throwable t) {
            notifyFailed(t);
        }
    });
}

From source file:c5db.eventLogging.EventLogService.java

License:Apache License

@Override
protected void doStart() {
    nioEventLoopGroup.next().execute(() -> {
        Bootstrap bootstrap = new Bootstrap();
        try {//ww  w . java  2  s  .c o  m
            bootstrap.group(nioEventLoopGroup).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, true)
                    .handler(new ChannelInitializer<DatagramChannel>() {
                        @Override
                        protected void initChannel(DatagramChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast("protostuffEncoder",
                                    new UdpProtostuffEncoder<>(EventLogEntry.getSchema(), false));
                        }
                    });

            bootstrap.bind(port).addListener(new GenericFutureListener<ChannelFuture>() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    broadcastChannel = future.channel();
                }
            });

            eventLogChannel.subscribe(fiber, msg -> {
                if (broadcastChannel == null) {
                    LOG.debug("Broadcast channel isn't read yet, dropped message");
                    return;
                }

                LOG.trace("Sending event {}", msg);
                broadcastChannel
                        .writeAndFlush(new UdpProtostuffEncoder.UdpProtostuffMessage<>(sendAddress, msg));
            });

            fiber.start();

            notifyStarted();
        } catch (Throwable t) {
            fiber.dispose();

            notifyFailed(t);
        }
    });
}

From source file:com.alibaba.rocketmq.remoting.netty.NettyUDPClient.java

License:Apache License

@Override
public void start() {
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(//
            nettyClientConfig.getClientWorkerThreads(), //
            new ThreadFactory() {

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override//from w  w  w  . j  a  v  a 2 s .co  m
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    Bootstrap handler = this.bootstrap.group(this.eventLoopGroupWorker).channel(NioDatagramChannel.class)//
            //
            .option(ChannelOption.SO_SNDBUF, nettyClientConfig.getClientSocketSndBufSize())
            //
            .handler(new ChannelInitializer<DatagramChannel>() {
                @Override
                public void initChannel(DatagramChannel ch) throws Exception {
                    ch.pipeline().addLast(//
                            defaultEventExecutorGroup, //
                            new NettyEncoder(), //
                            new NettyDecoder(), //
                            //new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()),//
                            new NettyConnetManageHandler(), //
                            new NettyClientHandler());
                }
            });

    if (this.channelEventListener != null) {
        this.nettyEventExecuter.start();
    }
}

From source file:com.alibaba.rocketmq.remoting.netty.NettyUDPServer.java

License:Apache License

@Override
public void start() {
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(//
            nettyServerConfig.getServerWorkerThreads(), //
            new ThreadFactory() {

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override//from w ww  .j av a2  s  .co m
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    Bootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroupWorker).channel(NioDatagramChannel.class)
                    //
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //
                    .option(ChannelOption.SO_REUSEADDR, true)
                    //
                    .option(ChannelOption.SO_KEEPALIVE, false)
                    //
                    .option(ChannelOption.SO_BROADCAST, true)
                    //
                    .option(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize())
                    //
                    .option(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize())
                    //
                    .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenUDPPort()))
                    .handler(new ChannelInitializer<DatagramChannel>() {
                        @Override
                        public void initChannel(DatagramChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    //
                                    defaultEventExecutorGroup, //
                                    new UDP2BufAdapt(), new NettyEncoder(), //
                                    //
                                    //new IdleStateHandler(0, 0, nettyServerConfig.getServerChannelMaxIdleTimeSeconds()),//
                                    //new NettyConnetManageHandler(), //
                                    new NettyServerHandler());
                        }
                    });

    if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) {
        // ????
        childHandler.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    }

    try {
        ChannelFuture sync = this.serverBootstrap.bind().sync();
        InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress();
        this.port = addr.getPort();
    } catch (InterruptedException e1) {
        throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1);
    }

    if (this.channelEventListener != null) {
        this.nettyEventExecuter.start();
    }

    // ?1??
    this.timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            try {
                NettyUDPServer.this.scanResponseTable();
            } catch (Exception e) {
                log.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);
}

From source file:com.github.mrstampy.kitchensync.netty.channel.initializer.ByteArrayMessageInitializer.java

License:Open Source License

@Override
protected void initChannel(DatagramChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    pipeline.addLast(new ByteArrayMessageHandler());
}

From source file:com.github.mrstampy.kitchensync.netty.channel.initializer.KiSyMessageInitializer.java

License:Open Source License

@Override
protected void initChannel(DatagramChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    pipeline.addLast(new KiSyMessageHandler());
}

From source file:com.github.mrstampy.kitchensync.netty.channel.initializer.StringMessageInitializer.java

License:Open Source License

@Override
protected void initChannel(DatagramChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    pipeline.addLast(new StringMessageHandler());
}

From source file:com.github.mrstampy.kitchensync.test.SslInitializer.java

License:Open Source License

@Override
protected void initChannel(DatagramChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    pipeline.addLast(new SslHandler(context.createSSLEngine()));
    pipeline.addLast(new KiSyMessageHandler());
}

From source file:groovyx.gpars.remote.netty.discovery.DiscoveryClient.java

License:Apache License

public DiscoveryClient(final int broadcastPort) {
    registeredPromises = new ConcurrentHashMap<String, DataflowVariable<InetSocketAddress>>();

    group = new NioEventLoopGroup();

    bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
            .handler(new ChannelInitializer<DatagramChannel>() {
                @Override//w ww .j a  v  a  2s.  co m
                protected void initChannel(DatagramChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast("decoder", new DiscoveryResponseDecoder());
                    pipeline.addLast("encoder", new DiscoveryRequestEncoder(broadcastPort));
                    pipeline.addLast("handler", new DiscoveryClientHandler(registeredPromises));
                }
            });

    channelFuture = bootstrap.bind(0);
}