Example usage for io.netty.buffer ByteBuf readableBytes

List of usage examples for io.netty.buffer ByteBuf readableBytes

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf readableBytes.

Prototype

public abstract int readableBytes();

Source Link

Document

Returns the number of readable bytes which is equal to (this.writerIndex - this.readerIndex) .

Usage

From source file:appeng.core.sync.packets.PacketPartialItem.java

License:Open Source License

public PacketPartialItem(final ByteBuf stream) {
    this.pageNum = stream.readShort();
    stream.readBytes(this.data = new byte[stream.readableBytes()]);
}

From source file:appeng.core.sync.packets.PacketValueConfig.java

License:Open Source License

public PacketValueConfig(final ByteBuf stream) throws IOException {
    final DataInputStream dis = new DataInputStream(
            new ByteArrayInputStream(stream.array(), stream.readerIndex(), stream.readableBytes()));
    this.Name = dis.readUTF();
    this.Value = dis.readUTF();
    // dis.close();
}

From source file:appeng.fmp.CableBusPart.java

License:Open Source License

@Override
public void writeDesc(final MCDataOutput packet) {
    final ByteBuf stream = Unpooled.buffer();

    try {/*from ww  w.ja  v  a2s  .co  m*/
        this.getCableBus().writeToStream(stream);
        packet.writeInt(stream.readableBytes());
        stream.capacity(stream.readableBytes());
        packet.writeByteArray(stream.array());
    } catch (final IOException e) {
        AELog.error(e);
    }
}

From source file:appeng.tile.AEBaseTile.java

License:Open Source License

/**
 * This builds a tag with the actual data that should be sent to the client for update syncs.
 * If the tile entity doesn't need update syncs, it returns null.
 *///from  w  ww  .ja  v  a  2s. c  om
private NBTTagCompound writeUpdateData() {
    final NBTTagCompound data = new NBTTagCompound();

    final ByteBuf stream = Unpooled.buffer();

    try {
        this.writeToStream(stream);
        if (stream.readableBytes() == 0) {
            return null;
        }
    } catch (final Throwable t) {
        AELog.debug(t);
    }

    stream.capacity(stream.readableBytes());
    data.setByteArray("X", stream.array());
    return data;
}

From source file:at.yawk.accordion.codec.unsafe.TestMessenger.java

License:Mozilla Public License

@Override
public Channel<ByteBuf> getChannel(String name) {
    return new Channel<ByteBuf>() {
        @Override//w w  w  .ja  v  a  2s . co  m
        public void publish(ByteBuf message) {
            byte[] data = Arrays.copyOf(message.array(), message.readableBytes());
            System.out.println(Arrays.toString(data));
            System.out.println(new String(data, StandardCharsets.UTF_8));
        }

        @Override
        public void subscribe(Consumer<ByteBuf> listener) {
        }
    };
}

From source file:at.yawk.accordion.compression.SnappyCompressor.java

License:Mozilla Public License

private static byte[] toArray(ByteBuf raw) {
    return Arrays.copyOfRange(raw.array(), raw.arrayOffset() + raw.readerIndex(),
            raw.arrayOffset() + raw.readerIndex() + raw.readableBytes());
}

From source file:at.yawk.accordion.distributed.ConnectionManager.java

License:Mozilla Public License

/**
 * Handle a decoded message from the given connection.
 *
 * @return a stream of connections the message should be forwarded to.
 *//*ww  w  . j a  v a 2s  .com*/
private Stream<Connection> handleDecodedMessage(Connection sender, ByteBuf decoded, long id) {
    // read channel name
    String channelName = InternalProtocol.readByteString(decoded);

    Log.debug(logger, () -> "Received packet " + Long.toHexString(id) + " in channel '" + channelName + "' ("
            + decoded.readableBytes() + " bytes)");

    // handle internally
    BiConsumer<ByteBuf, Connection> internalHandler = internalHandlers.get(channelName);
    if (internalHandler != null) {
        internalHandler.accept(decoded, sender);
        // internally handled, do not handle in user code or forward
        return Stream.empty();
    }

    // handle payload in listeners
    Collection<Consumer<ByteBuf>> subs = listeners.getOrDefault(channelName, Collections.emptySet());
    if (!subs.isEmpty()) {
        subs.forEach(listener -> listener.accept(decoded.copy()));
    }
    return getConnectionsSubscribedTo(channelName);
}

From source file:at.yawk.accordion.distributed.ConnectionManager.java

License:Mozilla Public License

/**
 * Send a packet to the given connections.
 *
 * @param channel   The encoded channel this packet should be sent on.
 * @param receivers The connections it should be forwarded to.
 * @param payload   The payload of the packet that will be received by the other nodes.
 *///from w  w  w. j  av  a2 s  .  c  om
void sendPacket(byte[] channel, Stream<Connection> receivers, ByteBuf payload) {
    long packetId = generateUniqueId();

    if (Log.isDebug(logger)) {
        List<Connection> connectionList = receivers.collect(Collectors.toList());
        logger.debug("Transmitting packet " + Long.toHexString(packetId) + " in channel '" + new String(channel)
                + "' (" + payload.readableBytes() + " bytes) to " + connectionList);
        receivers = connectionList.stream();
    }
    // encode
    ByteBuf full = InternalProtocol.encodePacket(channel, packetId, payload, compressor);

    // transmit to all given connections
    receivers.forEach(connection -> copyAndSend(connection, full));
}

From source file:at.yawk.accordion.distributed.ConnectionManager.java

License:Mozilla Public License

/**
 * Send a raw packet (with header fields already included) to the given connection. The given ByteBuf will not be
 * modified.//from  w w w.jav a  2s  .  c om
 */
private void copyAndSend(Connection connection, ByteBuf full) {
    ByteBuf copy = full.copy();
    // 8 for packet ID, at least 1 for channel name or we're doing something wrong
    assert copy.readableBytes() > 9 : Arrays.toString(copy.array());
    connection.send(copy);
}

From source file:at.yawk.accordion.minecraft.AccordionBungee.java

License:Mozilla Public License

public static AccordionApi createApi(Plugin plugin) {
    InetSocketAddress host = plugin.getProxy().getConfig().getListeners().stream().findAny().get().getHost();
    AccordionApi api = new AccordionApi().mcPort(host.getPort()).logger(plugin.getLogger()).listen(true)
            .tier(AccordionApi.DEFAULT_TIER_BUNGEE);

    // hack to get bungee thread group
    Object lock = new Object();
    plugin.getProxy().getScheduler().runAsync(plugin, () -> {
        api.threadGroup(Thread.currentThread().getThreadGroup());
        synchronized (lock) {
            lock.notifyAll();/*from  w w  w  .j a v a 2  s. com*/
        }
    });
    //noinspection SynchronizationOnLocalVariableOrMethodParameter
    synchronized (lock) {
        try {
            lock.wait();
        } catch (InterruptedException ignored) {
        }
    }

    // TODO reliable autostart
    plugin.getProxy().getScheduler().schedule(plugin, api::tryAutoStart, 3, TimeUnit.SECONDS);

    plugin.getProxy().getPluginManager().registerListener(plugin, new Listener() {
        @EventHandler
        public void onPluginMessage(PluginMessageEvent event) {
            // filter malicious peer packets from client
            if (event.getTag().equals(AccordionApi.PEER_DISCOVERY_PLUGIN_CHANNEL)) {
                event.setCancelled(true);
            }
        }

        @EventHandler
        public void onSwitch(ServerSwitchEvent event) {
            if (!api.isAutomaticDiscovery()) {
                return;
            }

            // send our known nodes to the server
            ByteBuf enc = api.getLocalNode().getKnownNodesEncoded();
            byte[] array = new byte[enc.readableBytes()];
            enc.readBytes(array);

            event.getPlayer().getServer().sendData(AccordionApi.PEER_DISCOVERY_PLUGIN_CHANNEL, array);
        }
    });

    return api;
}