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:org.kaazing.messaging.driver.transport.netty.udp.NettySendingTransport.java

License:Apache License

public NettySendingTransport(NettyTransportContext nettyTransportContext, String address,
        String targetTransportHandleId) {
    this.nettyTransportContext = nettyTransportContext;
    this.address = address;
    this.targetTransportHandleId = targetTransportHandleId;

    final URI uri;
    try {/* w w  w  . j  a  v a 2s  .  c om*/
        uri = new URI(address);
        final int uriPort = uri.getPort();
        if (uriPort < 0) {
            throw new IllegalArgumentException("Port must be specified");
        }
        final InetAddress hostAddress = InetAddress.getByName(uri.getHost());
        this.inetSocketAddress = new InetSocketAddress(hostAddress, uriPort);
        sendingChannel = nettyTransportContext.getBootstrap().bind(0).sync().channel();
        //this.nettyTransportContext.getEventLoopGroup().register(sendingChannel);
    } catch (URISyntaxException e) {
        LOGGER.error("Error parsing address", e);
        throw new IllegalArgumentException("Failed to parse address: " + address);
    } catch (UnknownHostException e) {
        LOGGER.error("Error resolving host", e);
        throw new IllegalArgumentException("Failed to resolve host: " + address);
    } catch (InterruptedException e) {
        LOGGER.error("Interrupted", e);
        throw new IllegalArgumentException("Interrupted while binding to address: " + address);
    }

    tlNettyMessage = new ThreadLocal<DatagramPacket>()
            .withInitial(() -> new DatagramPacket(Unpooled.buffer(), inetSocketAddress));

}

From source file:org.lanternpowered.server.network.query.QueryHandler.java

License:MIT License

private void handleHandshake(ChannelHandlerContext ctx, DatagramPacket packet, int sessionId) {
    int challengeToken = queryServer.generateChallengeToken(packet.sender());
    ByteBuf out = ctx.alloc().buffer();/*from ww  w.j a  v  a 2s.  com*/
    out.writeByte(ACTION_HANDSHAKE);
    out.writeInt(sessionId);
    writeString(out, String.valueOf(challengeToken));
    ctx.write(new DatagramPacket(out, packet.sender()));
}

From source file:org.lanternpowered.server.network.query.QueryHandler.java

License:MIT License

private void handleBasicStats(ChannelHandlerContext ctx, DatagramPacket packet, int sessionId) {
    LanternServer server = this.queryServer.getGame().getServer();

    // TODO: Find out how to support the size and max size properties
    final QueryServerEvent.Basic event = SpongeEventFactory.createQueryServerEventBasic(
            Cause.source(ctx.channel().remoteAddress()).build(),
            (InetSocketAddress) ctx.channel().localAddress(), "SMP", this.getWorldName(),
            server.getMotd().toPlain(), server.getMaxPlayers(), Integer.MAX_VALUE,
            server.getOnlinePlayers().size(), 0);
    Sponge.getEventManager().post(event);

    final InetSocketAddress address = event.getAddress();

    ByteBuf buf = ctx.alloc().buffer();/*from  www .ja  v  a2 s  .c  om*/
    buf.writeByte(ACTION_STATS);
    buf.writeInt(sessionId);
    writeString(buf, event.getMotd());
    writeString(buf, event.getGameType());
    writeString(buf, event.getMap());
    writeString(buf, String.valueOf(event.getPlayerCount()));
    writeString(buf, String.valueOf(event.getMaxPlayerCount()));
    buf.writeShortLE(address.getPort());
    writeString(buf, address.getHostString());
    ctx.write(new DatagramPacket(buf, packet.sender()));
}

From source file:org.lanternpowered.server.network.query.QueryHandler.java

License:MIT License

private void handleFullStats(ChannelHandlerContext ctx, DatagramPacket packet, int sessionId) {
    final LanternGame game = this.queryServer.getGame();
    final LanternServer server = game.getServer();
    final Platform platform = game.getPlatform();

    final PluginContainer api = platform.getContainer(Platform.Component.API);
    final PluginContainer impl = platform.getContainer(Platform.Component.IMPLEMENTATION);
    final PluginContainer mc = platform.getContainer(Platform.Component.GAME);

    final StringBuilder plugins = new StringBuilder().append(impl.getName()).append(" ")
            .append(impl.getVersion()).append(" on ").append(api.getName()).append(" ")
            .append(api.getVersion());//from w w w. jav  a 2 s . c om

    if (this.showPlugins) {
        final List<PluginContainer> containers = new ArrayList<>(game.getPluginManager().getPlugins());
        containers.remove(api);
        containers.remove(impl);
        containers.remove(mc);

        char delim = ':';
        for (PluginContainer plugin : containers) {
            plugins.append(delim).append(' ').append(plugin.getName());
            delim = ';';
        }
    }

    final List<String> playerNames = server.getOnlinePlayers().stream().map(CommandSource::getName)
            .collect(Collectors.toList());
    final Cause cause = Cause.source(ctx.channel().remoteAddress()).build();

    final QueryServerEvent.Full event = SpongeEventFactory.createQueryServerEventFull(cause,
            (InetSocketAddress) ctx.channel().localAddress(), new HashMap<>(), "MINECRAFT", "SMP",
            getWorldName(), server.getMotd().toPlain(), playerNames, plugins.toString(),
            mc.getVersion().orElse("unknown"), server.getMaxPlayers(), Integer.MAX_VALUE, playerNames.size(),
            0);
    final InetSocketAddress address = event.getAddress();

    final Map<String, Object> data = new LinkedHashMap<>();
    data.put("hostname", event.getMotd());
    data.put("gametype", event.getGameType());
    data.put("game_id", event.getGameId());
    data.put("version", event.getVersion());
    data.put("plugins", event.getPlugins());
    data.put("map", event.getMap());
    data.put("numplayers", event.getPlayerCount());
    data.put("maxplayers", event.getMaxPlayerCount());
    data.put("hostport", address.getPort());
    data.put("hostip", address.getHostString());
    event.getCustomValuesMap().entrySet().stream().filter(entry -> !data.containsKey(entry.getKey()))
            .forEach(entry -> data.put(entry.getKey(), entry.getValue()));

    final ByteBuf buf = ctx.alloc().buffer();
    buf.writeByte(ACTION_STATS);
    buf.writeInt(sessionId);
    // constant: splitnum\x00\x80\x00
    buf.writeBytes(new byte[] { 0x73, 0x70, 0x6C, 0x69, 0x74, 0x6E, 0x75, 0x6D, 0x00, (byte) 0x80, 0x00 });
    for (Entry<String, Object> e : data.entrySet()) {
        writeString(buf, e.getKey());
        writeString(buf, String.valueOf(e.getValue()));
    }
    buf.writeByte(0);
    // constant: \x01player_\x00\x00
    buf.writeBytes(new byte[] { 0x01, 0x70, 0x6C, 0x61, 0x79, 0x65, 0x72, 0x5F, 0x00, 0x00 });
    for (Player player : game.getServer().getOnlinePlayers()) {
        writeString(buf, player.getName());
    }
    buf.writeByte(0);
    ctx.write(new DatagramPacket(buf, packet.sender()));
}

From source file:org.mbmg.udp.client.Client.java

License:Apache License

public void run() {
    try {/*from   w w  w.j ava 2 s .  co  m*/
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioDatagramChannel.class).handler(new ClientHandler());

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

            InetSocketAddress address = new InetSocketAddress("localhost", port);

            String sendingContent = "4:#STD:123456,511;L:308;TM:1404120015;D:1;T:01;C:44;A00:0.632;A01:00000;A02:00000;A03:00000;A04:00000;A05:00000;A06:00000;A07:00000;A08:00000;A09:00000;A10:00000;A11:00000;A12:00000;A13:22.31;A14:22.68;P01:00000000;P02:00000000;P03:00000000;P04:00000000;P05:00000000;P06:00000000;K01:13300000000000000;O01:0000;28#\r\n";

            ch.writeAndFlush(
                    new DatagramPacket(Unpooled.copiedBuffer(sendingContent, CharsetUtil.UTF_8), address))
                    .sync();

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

From source file:org.onesec.raven.rtp.OutboundPacketBuilderHandler.java

License:Apache License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    ctx.writeAndFlush(new DatagramPacket((ByteBuf) msg, remoteSocket));
}

From source file:org.onesec.raven.rtp.RtpInboundHandlerTest.java

License:Apache License

@Test
public void test() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup(4);
    Bootstrap serverBootstrap = createServerBootstrap(group);
    Bootstrap clientBootstrap = createClientBootstrap(group);

    ChannelFuture future = serverBootstrap.bind(Inet4Address.getLocalHost(), BIND_PORT);
    future.await();/*w  w w  .j a v a  2s  . c  o m*/
    serverChannel = future.channel();
    RtpInboundHandler handler = serverChannel.pipeline().get(RtpInboundHandler.class);
    assertNotNull(handler);
    handler.getInStream().setTransferHandler(new Handler());

    //        ChannelFuture clientFuture = clientBootstrap.connect(Inet4Address.getLocalHost(), BIND_PORT);
    ChannelFuture clientFuture = clientBootstrap.bind(Inet4Address.getLocalHost(), BIND_PORT + 1);
    clientChannel = clientFuture.await().channel();
    assertNotNull(clientChannel);
    InetSocketAddress addr = new InetSocketAddress(localhost, BIND_PORT);
    ByteBuf writeBuf = clientChannel.alloc().buffer(5).writeBytes(TEST_BUFFER);
    clientChannel.writeAndFlush(new DatagramPacket(writeBuf, addr)).addListener(new GenericFutureListener() {
        public void operationComplete(Future future) throws Exception {
            clientChannel.close();
        }
    });

    serverChannel.closeFuture().await();
    assertNotNull(receivedBuffer.get());
    assertArrayEquals(TEST_BUFFER, receivedBuffer.get());

}

From source file:org.onosproject.lisp.ctl.impl.LispMessageDecoderTest.java

License:Apache License

private DatagramPacket convToDatagram(ByteBuf byteBuf) {
    InetSocketAddress source = new InetSocketAddress(0);
    return new DatagramPacket(byteBuf, source);
}

From source file:org.onosproject.lisp.ctl.impl.LispMessageEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Object msg, List out) throws Exception {
    if (!(msg instanceof List)) {
        ByteBuf byteBuf = Unpooled.buffer();
        ((LispMessage) msg).writeTo(byteBuf);
        out.add(new DatagramPacket(byteBuf, ((LispMessage) msg).getSender()));
        return;//w  ww .ja v  a2s  .  c o  m
    }

    List<LispMessage> msgList = (List<LispMessage>) msg;

    for (LispMessage message : msgList) {
        if (message != null) {
            ByteBuf byteBuf = Unpooled.buffer();
            message.writeTo(byteBuf);
            out.add(new DatagramPacket(byteBuf, message.getSender()));
        }
    }
}

From source file:org.onosproject.lisp.ctl.LispMessageEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Object msg, List out) throws Exception {
    if (!(msg instanceof List)) {
        ByteBuf byteBuf = Unpooled.buffer();
        ((LispMessage) msg).writeTo(byteBuf);
        out.add(new DatagramPacket(byteBuf, ((LispMessage) msg).getSender()));
        return;//from   ww w  .j  a va2 s  .  c o m
    }

    List<LispMessage> msgList = (List<LispMessage>) msg;

    for (LispMessage message : msgList) {
        if (message != null) {
            ByteBuf byteBuf = Unpooled.buffer();
            message.writeTo(byteBuf);
            out.add(new DatagramPacket(byteBuf, ((LispMessage) msg).getSender()));
        }
    }
}