Example usage for io.netty.channel ChannelOption SO_BROADCAST

List of usage examples for io.netty.channel ChannelOption SO_BROADCAST

Introduction

In this page you can find the example usage for io.netty.channel ChannelOption SO_BROADCAST.

Prototype

ChannelOption SO_BROADCAST

To view the source code for io.netty.channel ChannelOption SO_BROADCAST.

Click Source Link

Usage

From source file:UdpServer.java

License:Open Source License

public void run() throws Exception {
    final NioEventLoopGroup group = new NioEventLoopGroup();
    //Create Actor System
    final ActorSystem system = ActorSystem.create("CapwapFSMActorSystem");
    final ActorRef PacketProcessorActor = system
            .actorOf(Props.create(CapwapMsgProcActor.class, "MessageProcessorActor"), "MessageProcessorActor");
    try {/*from  w ww .  ja  va 2 s.com*/
        final Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChannelInitializer<NioDatagramChannel>() {
                    @Override
                    public void initChannel(final NioDatagramChannel ch) throws Exception {

                        ChannelPipeline p = ch.pipeline();
                        createActorAndHandler(p);
                        //p.addLast(new IncommingPacketHandler(PacketProcessorActor));
                    }
                });

        // Bind and start to accept incoming connections.
        Integer pPort = port;
        InetAddress address = InetAddress.getLoopbackAddress();
        System.out.printf("\n\nwaiting for message %s %s\n\n", String.format(pPort.toString()),
                String.format(address.toString()));
        b.bind(address, port).sync().channel().closeFuture().await();

    } finally {
        System.out.print("In Server Finally");
    }
}

From source file:FSMTester.java

License:Open Source License

public void run() throws Exception {
    final NioEventLoopGroup group = new NioEventLoopGroup();
    //Create Actor System
    final ActorSystem system = ActorSystem.create("CapwapFSMActorSystem");
    final ActorRef PacketProcessorActor = system
            .actorOf(Props.create(CapwapMsgProcActor.class, "MessageProcessorActor"), "MessageProcessorActor");
    try {//from  w w  w.j  a v  a2 s.  com
        final Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChannelInitializer<NioDatagramChannel>() {
                    @Override
                    public void initChannel(final NioDatagramChannel ch) throws Exception {

                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new IncommingPacketFSMHandler(PacketProcessorActor));
                    }
                });

        // Bind and start to accept incoming connections.
        Integer pPort = port;
        InetAddress address = InetAddress.getLoopbackAddress();
        System.out.printf("\n\nwaiting for message %s %s\n\n", String.format(pPort.toString()),
                String.format(address.toString()));
        b.bind(address, port).sync().channel().closeFuture().await();

    } finally {
        System.out.print("In Server Finally");
    }
}

From source file:books.netty.protocol.udp.ChineseProverbClient.java

License:Apache License

public void run(int port) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*from w ww  . j  ava 2 s  . c  o m*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChineseProverbClientHandler());
        Channel ch = b.bind(0).sync().channel();
        // ?UDP?
        ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("?", CharsetUtil.UTF_8),
                new InetSocketAddress("255.255.255.255", port))).sync();
        if (!ch.closeFuture().await(15000)) {
            System.out.println("!");
        }
    } finally {
        group.shutdownGracefully();
    }
}

From source file:books.netty.protocol.udp.ChineseProverbServer.java

License:Apache License

public void run(int port) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {//  ww  w.  j  a va  2  s  .  c o  m
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChineseProverbServerHandler());
        b.bind(port).sync().channel().closeFuture().await();
    } finally {
        group.shutdownGracefully();
    }
}

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//www  . java2 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 ww .  j  av a 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("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 {//from   w  ww.  j a  va  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:ccostello.server.GameServer.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*w  w  w.  j  a v  a2  s. c o m*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .handler(new NetworkGameServerHandler());

        System.out.println("Listening...");
        b.bind(port).sync().channel().closeFuture().await();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:cl.uandes.so.server.LoginServer.java

public void run() throws Exception {
    final EventLoopGroup group = new NioEventLoopGroup(); // (1)

    try {//from   ww  w . j  av  a  2s . c  o  m
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                System.out.println("Login Server will stop in 60 seconds...");
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(LoginServer.class.getName()).log(Level.SEVERE, null, ex);
                }
                group.shutdownGracefully();

            }
        });
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                int counter = 1;
                while (counter < 10) {
                    System.out.println("Time : " + counter);
                    try {
                        Thread.sleep(1000);
                        counter++;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t1.start();
        t2.start();
        Bootstrap b = new Bootstrap(); // (2)
        b.group(group).channel(NioDatagramChannel.class) // (3)
                .option(ChannelOption.SO_BROADCAST, true).handler(new LoginServerHandler(multicastgroup));

        // Bind and start to accept incoming connections.
        b.bind(port).sync().channel().closeFuture().await(); // (7)

    } finally {
        group.shutdownGracefully();
    }
}

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//  www .  j  a  va2s .c  o 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);
}