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:com.liferay.sync.engine.lan.server.discovery.LanDiscoveryBroadcaster.java

License:Open Source License

public void broadcast(int port) throws Exception {
    if ((_channel == null) || !_channel.isActive()) {
        _initialize();//from w ww .jav a  2 s.  com
    }

    byte[] bytes = JSONUtil.writeValueAsBytes(LanClientUtil.createSyncLanClient(port));

    DatagramPacket datagramPacket = new DatagramPacket(Unpooled.copiedBuffer(bytes),
            new InetSocketAddress("255.255.255.255", PropsValues.SYNC_LAN_SERVER_PORT));

    ChannelFuture channelFuture = _channel.writeAndFlush(datagramPacket);

    channelFuture.sync();
}

From source file:com.lunex.inputprocessor.testdemo.QuoteOfTheMomentClient.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup group = new NioEventLoopGroup();
    try {//from ww w  .j  ava  2 s. c o m
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .handler(new QuoteOfTheMomentClientHandler());

        Channel ch = b.bind(0).sync().channel();

        // Broadcast the QOTM request to port 8080.
        ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
                new InetSocketAddress("255.255.255.255", PORT))).sync();

        // QuoteOfTheMomentClientHandler will close the DatagramChannel when
        // a
        // response is received. If the channel is not closed within 5
        // seconds,
        // print an error message and quit.
        if (!ch.closeFuture().await(5000)) {
            System.err.println("QOTM request timed out.");
        }
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.lunex.inputprocessor.testdemo.QuoteOfTheMomentServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
    System.err.println(packet);//from   w  w  w . j av a  2  s .c  om
    String packageContent = packet.content().toString(CharsetUtil.UTF_8);
    if ("QOTM?".equals(packageContent)) {
        ctx.write(new DatagramPacket(Unpooled.copiedBuffer("QOTM: " + nextQuote(), CharsetUtil.UTF_8),
                packet.sender()));
    }
}

From source file:com.mpush.api.protocol.UDPPacket.java

License:Apache License

@Override
public Object toFrame(Channel channel) {
    int capacity = cmd == HEARTBEAT.cmd ? 1 : HEADER_LEN + getBodyLength();
    ByteBuf out = channel.alloc().buffer(capacity, capacity);
    encodePacket(this, out);
    return new DatagramPacket(out, sender());
}

From source file:com.netflix.client.netty.udp.HelloUdpServer.java

License:Apache License

public UdpServer<DatagramPacket, DatagramPacket> createServer() {
    UdpServer<DatagramPacket, DatagramPacket> server = RxNetty.createUdpServer(port,
            new ConnectionHandler<DatagramPacket, DatagramPacket>() {
                @Override/* www . j a  va  2s  .co  m*/
                public Observable<Void> handle(
                        final ObservableConnection<DatagramPacket, DatagramPacket> newConnection) {
                    return newConnection.getInput().flatMap(new Func1<DatagramPacket, Observable<Void>>() {
                        @Override
                        public Observable<Void> call(final DatagramPacket received) {
                            return Observable.interval(delay, TimeUnit.MILLISECONDS).take(1)
                                    .flatMap(new Func1<Long, Observable<Void>>() {
                                        @Override
                                        public Observable<Void> call(Long aLong) {
                                            InetSocketAddress sender = received.sender();
                                            System.out.println("Received datagram. Sender: " + sender);
                                            ByteBuf data = newConnection.getChannelHandlerContext().alloc()
                                                    .buffer(WELCOME_MSG_BYTES.length);
                                            data.writeBytes(WELCOME_MSG_BYTES);
                                            return newConnection
                                                    .writeAndFlush(new DatagramPacket(data, sender));
                                        }
                                    });
                        }
                    });
                }
            });
    System.out.println("UDP hello server started at port: " + port);
    return server;
}

From source file:com.netflix.ribbon.transport.netty.udp.HelloUdpServer.java

License:Apache License

public UdpServer<DatagramPacket, DatagramPacket> createServer() {
    UdpServer<DatagramPacket, DatagramPacket> server = RxNetty.createUdpServer(port,
            new ConnectionHandler<DatagramPacket, DatagramPacket>() {
                @Override//from   ww  w .  jav  a  2  s.c  o  m
                public Observable<Void> handle(
                        final ObservableConnection<DatagramPacket, DatagramPacket> newConnection) {
                    return newConnection.getInput().flatMap(new Func1<DatagramPacket, Observable<Void>>() {
                        @Override
                        public Observable<Void> call(final DatagramPacket received) {
                            return Observable.interval(delay, TimeUnit.MILLISECONDS).take(1)
                                    .flatMap(new Func1<Long, Observable<Void>>() {
                                        @Override
                                        public Observable<Void> call(Long aLong) {
                                            InetSocketAddress sender = received.sender();
                                            System.out.println("Received datagram. Sender: " + sender);
                                            ByteBuf data = newConnection.getChannel().alloc()
                                                    .buffer(WELCOME_MSG_BYTES.length);
                                            data.writeBytes(WELCOME_MSG_BYTES);
                                            return newConnection
                                                    .writeAndFlush(new DatagramPacket(data, sender));
                                        }
                                    });
                        }
                    });
                }
            });
    System.out.println("UDP hello server started at port: " + port);
    return server;
}

From source file:com.srotya.linea.network.InternalUDPTransportClient.java

License:Apache License

@Override
public void onEvent(Event event, long sequence, boolean endOfBatch) throws Exception {
    Integer workerId = (Integer) event.getHeaders().get(Constants.FIELD_DESTINATION_WORKER_ID);
    try {// w  w w .  j a va 2s . c  o m
        ByteBuffer buf = bufferMap.get(workerId);
        MutableShort bufferEventCount = bufferCounterMap.get(workerId);
        byte[] bytes = InternalTCPTransportServer.KryoObjectEncoder.eventToByteArray(event,
                InternalTCPTransportServer.COMPRESS);
        if (packingEnabled) {
            if (bytes.length > 1024) {
                // discard
                System.err.println("Discarded event");
            }
            if (buf.remaining() - bytes.length >= 0) {
                buf.put(bytes);
                bufferEventCount.incrementAndGet();
            } else {
                buf.putShort(0, bufferEventCount.getVal());
                buf.rewind();
                channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(buf),
                        new InetSocketAddress(columbus.getWorkerMap().get(workerId).getWorkerAddress(),
                                columbus.getWorkerMap().get(workerId).getDataPort())));
                bufferEventCount.setVal((short) 0);
                buf.rewind();
                buf.putShort(bufferEventCount.getVal());
                buf.put(bytes);
            }
        } else {
            buf.rewind();
            buf.putShort((short) 1);
            buf.put(bytes);
            buf.rewind();
            channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(buf),
                    new InetSocketAddress(columbus.getWorkerMap().get(workerId).getWorkerAddress(),
                            columbus.getWorkerMap().get(workerId).getDataPort())));
        }

    } catch (Exception e) {
        System.out.println("Exception:" + event + "\tSelf worker ID:" + columbus.getSelfWorkerId() + "\t"
                + workerId + "\t" + columbus.getWorkerMap());
        throw e;
    }
}

From source file:com.vela.iot.active.netty.coap.CoAPClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    int bossCount = 1;
    if (args.length > 3) {
        bossCount = Integer.parseInt(args[3]);
    }//w ww . java 2 s  .com
    int bufSize = 655350;
    if (args.length > 4) {
        bufSize = Integer.parseInt(args[4]);
    }
    EventLoopGroup group = new NioEventLoopGroup(bossCount);
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_RCVBUF, bufSize)
                .option(ChannelOption.SO_SNDBUF, bufSize).handler(new CoAPClientHandler());
        Channel ch = b.bind(0).sync().channel();
        String ip = "192.168.2.185";
        if (args.length > 0) {
            ip = args[0];
        }
        if (args.length > 1) {
            REQ_NUM = Integer.parseInt(args[1]);
        }
        int concNum = 10;
        if (args.length > 2) {
            concNum = Integer.parseInt(args[2]);
        }
        InetSocketAddress add = new InetSocketAddress(ip, PORT);

        long start = System.nanoTime();
        ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("start", CharsetUtil.UTF_8), add));
        for (int i = 0; i < REQ_NUM; i++) {
            ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                    "auth/gw/active?devSn=wZud4fM6SUuvvvBoFyGNYw&devKey=8I8LLGb7QaOZw6wgYInDrQ&devInfo=" + i,
                    CharsetUtil.UTF_8), add));
            if (i % concNum == 0)
                Thread.sleep(0, 1);
        }
        ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("end", CharsetUtil.UTF_8), add));
        // LOGGER.info(":{},:{}", REQ_NUM, System.nanoTime() -
        // start);
        System.out.printf(":%d,:%d", REQ_NUM, System.nanoTime() - start);
        if (!ch.closeFuture().await(5000)) {
            System.err.println("QOTM request timed out.");
        }
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.whirvis.jraknet.client.RakNetClient.java

License:Open Source License

/**
 * Sends a Netty message over the channel raw.
 * <p>//from   www  . j av a 2  s. c o m
 * This should be used sparingly, as if it is used incorrectly it could
 * break server peers entirely. In order to send a message to a peer, use
 * one of the
 * {@link com.whirvis.jraknet.peer.RakNetPeer#sendMessage(Reliability, ByteBuf)
 * sendMessage()} methods.
 * 
 * @param buf
 *            the buffer to send.
 * @param address
 *            the address to send the buffer to.
 * @throws NullPointerException
 *             if the <code>buf</code>, <code>address</code>, or IP address
 *             of <code>address</code> are <code>null</code>.
 */
public final void sendNettyMessage(ByteBuf buf, InetSocketAddress address) throws NullPointerException {
    if (buf == null) {
        throw new NullPointerException("Buffer cannot be null");
    } else if (address == null) {
        throw new NullPointerException("Address cannot be null");
    } else if (address.getAddress() == null) {
        throw new NullPointerException("IP address cannot be null");
    }
    channel.writeAndFlush(new DatagramPacket(buf, address));
    log.debug("Sent netty message with size of " + buf.capacity() + " bytes (" + (buf.capacity() * 8)
            + " bits) to " + address);
}

From source file:com.whirvis.jraknet.discovery.DiscoveryThread.java

License:Open Source License

/**
 * {@inheritDoc}//from   w w  w  .  j a  v  a2  s.c  o m
 * 
 * @throws IllegalStateException
 *             if the thread is still alive, yet the reference in the
 *             discovery thread is not the same as the reference to this
 *             thread.
 */
@Override
public void run() throws IllegalStateException {
    log.debug("Started discovery thread");
    while (!Discovery.LISTENERS.isEmpty() && !Discovery.DISCOVERY_ADDRESSES.isEmpty()
            && Discovery.discoveryMode != DiscoveryMode.DISABLED && !this.isInterrupted()) {
        if (Discovery.thread != this) {
            /*
             * Normally we would just break the thread here, but if two of
             * these are running it indicates a synchronization problem in
             * the code.
             */
            throw new IllegalStateException(
                    "Discovery thread must be this while running, are there multiple discovery threads running?");
        }
        try {
            Thread.sleep(0, 1); // Save CPU usage
        } catch (InterruptedException e) {
            this.interrupt(); // Interrupted during sleep
            continue;
        }
        long currentTime = System.currentTimeMillis();

        // Forget servers that have taken too long to respond back
        ArrayList<InetSocketAddress> forgottenServers = new ArrayList<InetSocketAddress>();
        for (InetSocketAddress address : Discovery.DISCOVERED.keySet()) {
            DiscoveredServer discovered = Discovery.DISCOVERED.get(address);
            if (discovered.hasTimedOut()) {
                forgottenServers.add(address);
                Discovery.callEvent(listener -> listener.onServerForgotten(discovered));
            }
        }
        Discovery.DISCOVERED.keySet().removeAll(forgottenServers);
        if (!forgottenServers.isEmpty()) {
            log.debug("Forgot " + forgottenServers.size() + " server"
                    + (forgottenServers.size() == 1 ? "" : "s"));
        }

        // Broadcast ping to local and external servers
        if (currentTime - lastPingBroadcast > 1000L) {
            UnconnectedPing ping = Discovery.getDiscoveryMode() == DiscoveryMode.OPEN_CONNECTIONS
                    ? new UnconnectedPingOpenConnections()
                    : new UnconnectedPing();
            ping.timestamp = Discovery.getTimestamp();
            ping.pingId = Discovery.getPingId();
            ping.encode();
            if (ping.failed()) {
                this.interrupt();
                Discovery.setDiscoveryMode(DiscoveryMode.DISABLED);
                log.error("Failed to encode unconnected ping, disabled discovery system");
            }
            for (InetSocketAddress address : Discovery.DISCOVERY_ADDRESSES.keySet()) {
                channel.writeAndFlush(new DatagramPacket(ping.buffer(), address));
            }
            log.debug("Sent unconnected ping to " + Discovery.DISCOVERY_ADDRESSES.size() + " server"
                    + (Discovery.DISCOVERY_ADDRESSES.size() == 1 ? "" : "s"));
            this.lastPingBroadcast = currentTime;
        }
    }

    /*
     * If there are no listeners, no discovery addresses, or discovery is
     * simply disabled, we will destroy this thread by nullifying the
     * scheduler's reference after the loop has been broken out of. If any
     * of these conditions changes, then a new discovery thread will be
     * created automatically.
     */
    channel.close();
    group.shutdownGracefully(0L, 1000L, TimeUnit.MILLISECONDS);
    this.channel = null;
    if (Discovery.thread == this) {
        Discovery.thread = null;
        log.debug("Terminated discovery thread");
    }
}