Example usage for io.netty.channel.socket DatagramPacket DatagramPacket

List of usage examples for io.netty.channel.socket DatagramPacket DatagramPacket

Introduction

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

Prototype

public DatagramPacket(ByteBuf data, InetSocketAddress recipient) 

Source Link

Document

Create a new instance with the specified packet data and recipient address.

Usage

From source file:dorkbox.network.Broadcast.java

License:Apache License

static List<BroadcastResponse> discoverHosts0(Logger logger, int udpPort, int discoverTimeoutMillis,
        boolean fetchAllServers) throws IOException {
    // fetch a buffer that contains the serialized object.
    ByteBuf buffer = Unpooled.buffer(1);
    buffer.writeByte(MagicBytes.broadcastID);

    List<BroadcastResponse> servers = new ArrayList<BroadcastResponse>();

    Enumeration<NetworkInterface> networkInterfaces;
    try {/*from  ww  w  .  ja  v  a 2  s. c om*/
        networkInterfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        if (logger != null) {
            logger.error("Host discovery failed.", e);
        }
        throw new IOException("Host discovery failed. No interfaces found.");
    }

    scan: for (NetworkInterface networkInterface : Collections.list(networkInterfaces)) {
        for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
            InetAddress address = interfaceAddress.getAddress();
            InetAddress broadcast = interfaceAddress.getBroadcast();

            // don't use IPv6!
            if (address instanceof Inet6Address) {
                if (logger != null) {
                    if (logger.isInfoEnabled()) {
                        logger.info("Not using IPv6 address: {}", address);
                    }
                }
                continue;
            }

            try {
                if (logger != null) {
                    if (logger.isInfoEnabled()) {
                        logger.info("Searching for host on [{}:{}]", address.getHostAddress(), udpPort);
                    }
                }

                EventLoopGroup group;
                Class<? extends Channel> channelClass;

                if (OS.isAndroid()) {
                    // android ONLY supports OIO (not NIO)
                    group = new OioEventLoopGroup(1);
                    channelClass = OioDatagramChannel.class;
                } else {
                    group = new NioEventLoopGroup(1);
                    channelClass = NioDatagramChannel.class;
                }

                Bootstrap udpBootstrap = new Bootstrap().group(group).channel(channelClass)
                        .option(ChannelOption.SO_BROADCAST, true).handler(new ClientDiscoverHostInitializer())
                        .localAddress(new InetSocketAddress(address, 0)); // pick random address. Not listen for broadcast.

                // we don't care about RECEIVING a broadcast packet, we are only SENDING one.
                ChannelFuture future;
                try {
                    future = udpBootstrap.bind();
                    future.await();
                } catch (InterruptedException e) {
                    if (logger != null) {
                        logger.error("Could not bind to random UDP address on the server.", e.getCause());
                    }
                    throw new IOException("Could not bind to random UDP address on the server.");
                }

                if (!future.isSuccess()) {
                    if (logger != null) {
                        logger.error("Could not bind to random UDP address on the server.", future.cause());
                    }
                    throw new IOException("Could not bind to random UDP address on the server.");
                }

                Channel channel1 = future.channel();

                if (broadcast != null) {
                    // try the "defined" broadcast first if we have it (not always!)
                    channel1.writeAndFlush(
                            new DatagramPacket(buffer, new InetSocketAddress(broadcast, udpPort)));

                    // response is received.  If the channel is not closed within 5 seconds, move to the next one.
                    if (!channel1.closeFuture().awaitUninterruptibly(discoverTimeoutMillis)) {
                        if (logger != null) {
                            if (logger.isInfoEnabled()) {
                                logger.info("Host discovery timed out.");
                            }
                        }
                    } else {
                        BroadcastResponse broadcastResponse = channel1.attr(ClientDiscoverHostHandler.STATE)
                                .get();
                        servers.add(broadcastResponse);
                    }

                    // keep going if we want to fetch all servers. Break if we found one.
                    if (!(fetchAllServers || servers.isEmpty())) {
                        channel1.close().await();
                        group.shutdownGracefully().await();
                        break scan;
                    }
                }

                // continue with "common" broadcast addresses.
                // Java 1.5 doesn't support getting the subnet mask, so try them until we find one.

                byte[] ip = address.getAddress();
                for (int octect = 3; octect >= 0; octect--) {
                    ip[octect] = -1; // 255.255.255.0

                    // don't error out on one particular octect
                    try {
                        InetAddress byAddress = InetAddress.getByAddress(ip);
                        channel1.writeAndFlush(
                                new DatagramPacket(buffer, new InetSocketAddress(byAddress, udpPort)));

                        // response is received.  If the channel is not closed within 5 seconds, move to the next one.
                        if (!channel1.closeFuture().awaitUninterruptibly(discoverTimeoutMillis)) {
                            if (logger != null) {
                                if (logger.isInfoEnabled()) {
                                    logger.info("Host discovery timed out.");
                                }
                            }
                        } else {
                            BroadcastResponse broadcastResponse = channel1.attr(ClientDiscoverHostHandler.STATE)
                                    .get();
                            servers.add(broadcastResponse);

                            if (!fetchAllServers) {
                                break;
                            }
                        }
                    } catch (Exception ignored) {
                    }
                }

                channel1.close().sync();
                group.shutdownGracefully(0, discoverTimeoutMillis, TimeUnit.MILLISECONDS);

            } catch (Exception ignored) {
            }

            // keep going if we want to fetch all servers. Break if we found one.
            if (!(fetchAllServers || servers.isEmpty())) {
                break scan;
            }
        }
    }

    if (logger != null && logger.isInfoEnabled() && !servers.isEmpty()) {
        StringBuilder stringBuilder = new StringBuilder(256);

        if (fetchAllServers) {
            stringBuilder.append("Discovered servers: (").append(servers.size()).append(")");

            for (BroadcastResponse server : servers) {
                stringBuilder.append("/n").append(server.remoteAddress).append(":");

                if (server.tcpPort > 0) {
                    stringBuilder.append(server.tcpPort);

                    if (server.udpPort > 0) {
                        stringBuilder.append(":");
                    }
                }
                if (server.udpPort > 0) {
                    stringBuilder.append(udpPort);
                }
            }
            logger.info(stringBuilder.toString());
        } else {
            BroadcastResponse server = servers.get(0);
            stringBuilder.append(server.remoteAddress).append(":");

            if (server.tcpPort > 0) {
                stringBuilder.append(server.tcpPort);

                if (server.udpPort > 0) {
                    stringBuilder.append(":");
                }
            }
            if (server.udpPort > 0) {
                stringBuilder.append(udpPort);
            }

            logger.info("Discovered server [{}]", stringBuilder.toString());
        }
    }

    return servers;
}

From source file:dorkbox.network.pipeline.udp.KryoEncoderUdp.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext context, Object message, List<Object> out) throws Exception {
    if (message != null) {
        try {// w  ww .ja  v a 2s . c  o  m
            ByteBuf outBuffer = context.alloc().ioBuffer(maxSize);

            // no size info, since this is UDP, it is not segmented
            writeObject(this.serializationManager, context, message, outBuffer);

            // have to check to see if we are too big for UDP!
            if (outBuffer.readableBytes() > maxSize) {
                String msg = "Object is TOO BIG FOR UDP! " + message.toString() + " (Max " + maxSize + ", was "
                        + outBuffer.readableBytes() + ")";
                LoggerFactory.getLogger(this.getClass()).error(msg);
                throw new IOException(msg);
            }

            DatagramPacket packet = new DatagramPacket(outBuffer,
                    (InetSocketAddress) context.channel().remoteAddress());
            out.add(packet);
        } catch (Exception e) {
            String msg = "Unable to serialize object of type: " + message.getClass().getName();
            LoggerFactory.getLogger(this.getClass()).error(msg, e);
            throw new IOException(msg, e);
        }
    }
}

From source file:eu.heronnet.module.kad.net.ClientImpl.java

License:Open Source License

private void broadcastOnInterface(InterfaceAddress interfaceAddress, Messages.Request request) {
    InetAddress broadcast = interfaceAddress.getBroadcast();
    if (broadcast != null) {
        ByteString messageId = request.getMessageId();
        udpBoostrap.handler(new ResponseHandler(messageId.toByteArray()));
        udpBoostrap.bind(0).addListener(new ChannelFutureListener() {
            @Override/*from w w w  .j  av a 2  s .  c  o m*/
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    final Channel channel = future.channel();

                    final ByteBuf requestBuffer = Unpooled.wrappedBuffer(request.toByteArray());
                    final DatagramPacket datagramPacket = new DatagramPacket(requestBuffer,
                            new InetSocketAddress(broadcast, selfNodeProvider.getSelf().getPort()));
                    channel.writeAndFlush(datagramPacket);
                    channel.close();
                    logger.debug("completed operation: {}", future.toString());
                } else {
                    logger.error("Error in channel bootstrap: {}", future.cause().getMessage());
                }
            }
        });
    }
}

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

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, DiscoveryRequest msg, List<Object> out) throws Exception {
    ByteBuf buf = Unpooled.copiedBuffer(msg.getActorUrl(), CharsetUtil.UTF_8);
    DatagramPacket packet = new DatagramPacket(buf, new InetSocketAddress("255.255.255.255", broadcastPort));
    out.add(packet);//  ww  w  . j a  va2 s  .  c o  m
}

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

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, DiscoveryResponseWithRecipient msg, List<Object> out)
        throws Exception {
    DiscoveryResponse response = msg.getResponse();
    ByteBuf portBuf = Unpooled.copyInt(response.getServerSocketAddress().getPort());
    ByteBuf urlBuf = Unpooled.copiedBuffer(response.getActorUrl(), CharsetUtil.UTF_8);

    DatagramPacket packet = new DatagramPacket(Unpooled.wrappedBuffer(portBuf, urlBuf), msg.getRecipient());
    out.add(packet);//from   w  ww. j  a v  a  2s  . c om
}

From source file:hms.webrtc.udp.proxy.remote.RemoteConfiguraitonClient.java

License:Apache License

public static void main(String[] args) {
    EventLoopGroup group = new NioEventLoopGroup();
    try {//from   w w w  .  j  a v  a  2s  . c om
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class)
                .handler(new SimpleChannelInboundHandler<DatagramPacket>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg)
                            throws Exception {
                        if ("SUCCESS".equals(msg.content().toString(CharsetUtil.UTF_8))) {
                            System.out.println("Sending configuration is success.");
                        }
                        ctx.close();
                    }
                });

        ch = b.bind(34001).sync().channel();

        ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("78737383:40000:40001", CharsetUtil.UTF_8),
                new InetSocketAddress("127.0.0.1", PORT))).sync();

        if (!ch.closeFuture().await(5000)) {
            Assert.fail("Rtp communication timeout");
        } else {
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:hms.webrtc.udp.proxy.RtpPartyA.java

License:Apache License

public static void main(String[] args) {
    EventLoopGroup group = new NioEventLoopGroup();
    try {//from   w  ww  .j  a  v a2s .c  om
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .handler(new RtpPartyAHandler());

        ch = b.bind(36001).sync().channel();

        ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(rtpDataByeArray),
                new InetSocketAddress("127.0.0.1", PORT))).sync();

        if (!ch.closeFuture().await(5000)) {
            Assert.fail("Rtp communication timeout");
        } else {

        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:io.advantageous.conekt.datagram.impl.DatagramSocketImpl.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public DatagramSocket send(Buffer packet, int port, String host, Handler<AsyncResult<DatagramSocket>> handler) {
    Objects.requireNonNull(host, "no null host accepted");
    ChannelFuture future = channel()//from   w  w w . j  a va  2 s  . c om
            .writeAndFlush(new DatagramPacket(packet.getByteBuf(), new InetSocketAddress(host, port)));
    addListener(future, handler);
    if (metrics.isEnabled()) {
        metrics.bytesWritten(null, new SocketAddressImpl(port, host), packet.length());
    }

    return this;
}

From source file:io.aos.netty5.qotm.QuoteOfTheMomentServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, DatagramPacket packet) {
    System.err.println(packet);// w  w  w  .  j a  va 2 s  .com
    if ("QOTM?".equals(packet.content().toString(CharsetUtil.UTF_8))) {
        ctx.write(new DatagramPacket(Unpooled.copiedBuffer("QOTM: " + nextQuote(), CharsetUtil.UTF_8),
                packet.sender()));
    }
}

From source file:io.atomix.cluster.messaging.impl.NettyBroadcastService.java

License:Apache License

@Override
public void broadcast(String subject, byte[] payload) {
    if (enabled) {
        Message message = new Message(subject, payload);
        byte[] bytes = SERIALIZER.encode(message);
        ByteBuf buf = serverChannel.alloc().buffer(4 + bytes.length);
        buf.writeInt(bytes.length).writeBytes(bytes);
        serverChannel.writeAndFlush(new DatagramPacket(buf, groupAddress));
    }/*from w  ww .  j av a  2 s  .  c om*/
}