Example usage for io.netty.buffer ByteBuf writeShort

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

Introduction

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

Prototype

public abstract ByteBuf writeShort(int value);

Source Link

Document

Sets the specified 16-bit short integer at the current writerIndex and increases the writerIndex by 2 in this buffer.

Usage

From source file:com.vethrfolnir.login.network.mu.send.SendServerLists.java

License:Open Source License

/**
 * @param context/*from  w ww . j  a  v a 2  s  .c  o  m*/
 * @param buff
 * @param params - GameNameService[0] 
 */
@Override
public void write(NetworkClient context, ByteBuf buff, Object... params) {
    GameNameService nameService = as(params[0]);

    int actualSize = nameService.liveServerSize();

    int size = (7 + (actualSize * 4));
    buff.writeByte(0xC2); // opcode

    //buff.writeShort(size);
    buff.writeByte(0x00); // size or empty ?
    buff.writeByte(size); // size?

    buff.writeByte(0xF4); // code
    buff.writeByte(0x06); // code

    buff.writeByte(0x00); // size or empty ?
    buff.writeByte(actualSize); // actual size

    // Formula
    // writeC((1 * 20 + 1));
    // 1 = server position on list, if changed to another nr it will subserver to that server id, else disapire
    // 20 = server to mult

    for (HashMap<Integer, GameServer> map : nameService.getLiveServers().values()) {
        for (GameServer server : map.values()) {
            int onlinePlayers = server.getOnlinePlayers() / server.getCap() * 100;

            buff.writeShort(server.getServerId());
            buff.writeShort(onlinePlayers);
        }
    }
}

From source file:com.vethrfolnir.network.WritePacket.java

License:Open Source License

public void writeSh(ByteBuf buff, int value) {
    buff.writeShort(value);
}

From source file:com.witjit.game.client.Client.java

License:Apache License

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

    EventLoopGroup group = new NioEventLoopGroup();
    try {//from w  w w .  ja  v  a  2 s. c  o  m
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ClientInitializer());

        // Start the connection attempt.
        Channel ch = b.connect(HOST, PORT).sync().channel();

        // Read commands from the stdin.
        ChannelFuture lastWriteFuture = null;
        //            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        //            for (;;) {
        //                String line = in.readLine();
        //                if (line == null) {
        //                    break;
        //                }
        //
        //                // Sends the received line to the server.
        //                lastWriteFuture = ch.writeAndFlush(line + "\r\n");
        //
        //                // If user typed the 'bye' command, wait until the server closes
        //                // the connection.
        //                if ("bye".equals(line.toLowerCase())) {
        //                    ch.closeFuture().sync();
        //                    break;
        //                }
        //            }

        ByteBuf outb = Unpooled.buffer(200);
        outb.writeShort(127);
        outb.writeShort(10);
        outb.writeInt(10001);
        outb.writeByte(40);
        outb.writeByte(50);
        // Sends the received line to the server.
        lastWriteFuture = ch.writeAndFlush(outb);
        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.sync();
        }

        // Wait until the connection is closed.
        ch.closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.witjit.game.client.EchoClient.java

License:Apache License

private static void sendData(Channel ch) throws InterruptedException {
    ByteBuf outb = Unpooled.buffer(200);
    outb.writeShort(127);
    outb.writeShort(10);/* www  . java  2s. c  o m*/
    outb.writeInt(10001);
    outb.writeByte(40);
    outb.writeByte(50);
    // Sends the received line to the server.
    ChannelFuture writeFuture = ch.writeAndFlush(outb);
    // Wait until all messages are flushed before closing the channel.
    if (writeFuture != null) {
        writeFuture.sync();
    }

}

From source file:com.witjit.game.server.communication.netty.handler.NodeChannelInitializer.java

protected void sendNodeInformation(Channel ch) throws Exception {
    ByteBuf buffer = Unpooled.buffer(4);
    buffer.writeShort(localNodeId);
    ch.writeAndFlush(buffer);//from   w  ww.j av a  2  s.c  o  m
}

From source file:com.yahoo.pulsar.common.api.Commands.java

License:Apache License

private static ByteBuf serializeCommandSendWithSize(BaseCommand.Builder cmdBuilder, ChecksumType checksumType,
        MessageMetadata msgMetadata, ByteBuf payload) {
    // / Wire format
    // [TOTAL_SIZE] [CMD_SIZE][CMD] [MAGIC_NUMBER][CHECKSUM] [METADATA_SIZE][METADATA] [PAYLOAD]

    BaseCommand cmd = cmdBuilder.build();
    int cmdSize = cmd.getSerializedSize();
    int msgMetadataSize = msgMetadata.getSerializedSize();
    int payloadSize = payload.readableBytes();
    int magicAndChecksumLength = ChecksumType.Crc32c.equals(checksumType) ? (2 + 4 /* magic + checksumLength*/)
            : 0;/*from   w ww  . ja  va  2 s . c o  m*/
    boolean includeChecksum = magicAndChecksumLength > 0;
    int headerContentSize = 4 + cmdSize + magicAndChecksumLength + 4 + msgMetadataSize; // cmdLength + cmdSize + magicLength +
    // checksumSize + msgMetadataLength +
    // msgMetadataSize
    int totalSize = headerContentSize + payloadSize;
    int headersSize = 4 + headerContentSize; // totalSize + headerLength
    int checksumReaderIndex = -1;

    ByteBuf headers = PooledByteBufAllocator.DEFAULT.buffer(headersSize, headersSize);
    headers.writeInt(totalSize); // External frame

    try {
        // Write cmd
        headers.writeInt(cmdSize);

        ByteBufCodedOutputStream outStream = ByteBufCodedOutputStream.get(headers);
        cmd.writeTo(outStream);
        cmd.recycle();
        cmdBuilder.recycle();

        //Create checksum placeholder
        if (includeChecksum) {
            headers.writeShort(magicCrc32c);
            checksumReaderIndex = headers.writerIndex();
            headers.writerIndex(headers.writerIndex() + checksumSize); //skip 4 bytes of checksum
        }

        // Write metadata
        headers.writeInt(msgMetadataSize);
        msgMetadata.writeTo(outStream);
        outStream.recycle();
    } catch (IOException e) {
        // This is in-memory serialization, should not fail
        throw new RuntimeException(e);
    }

    ByteBuf command = DoubleByteBuf.get(headers, payload);

    // write checksum at created checksum-placeholder
    if (includeChecksum) {
        headers.markReaderIndex();
        headers.readerIndex(checksumReaderIndex + checksumSize);
        int metadataChecksum = computeChecksum(headers);
        int computedChecksum = resumeChecksum(metadataChecksum, payload);
        // set computed checksum
        headers.setInt(checksumReaderIndex, computedChecksum);
        headers.resetReaderIndex();
    }
    return command;
}

From source file:com.yea.remote.netty.codec.NettyMessageEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf sendBuf) throws Exception {
    if (msg == null || msg.getHeader() == null) {
        throw new Exception("The encode message is null");
    }//from w  w  w  .ja v  a 2  s .  co  m
    ISerializer serializer = serializePool.borrow();
    try {
        long basedate = new Date().getTime();
        sendBuf.writeInt((msg.getHeader().getCrcCode()));// 4
        sendBuf.writeInt((msg.getHeader().getLength()));// 4Header+BodyHeader18
        sendBuf.writeBytes((msg.getHeader().getSessionID()));// 16
        sendBuf.writeByte((msg.getHeader().getType()));// 1
        sendBuf.writeByte((msg.getHeader().getPriority()));// 1
        sendBuf.writeByte((msg.getHeader().getResult()));// 1
        if (compressionAlgorithm != null && compressionAlgorithm.code() > 0) {
            // 
            serializer.setCompress(new Compress().setCompressionAlgorithm(compressionAlgorithm.algorithm()));
            sendBuf.writeByte(compressionAlgorithm.ordinal());
        } else {
            sendBuf.writeByte(RemoteConstants.CompressionAlgorithm.NONE.ordinal());
        }
        sendBuf.writeLong(basedate);// 8??
        if (msg.getHeader().getAttachment() != null && !msg.getHeader().getAttachment().isEmpty()) {
            sendBuf.writeByte(msg.getHeader().getAttachment().size());
            Map<String, Number> mapDateType = new HashMap<String, Number>();// Date
            Map<String, String> mapStringType = new HashMap<String, String>();// String

            int lengthPos = sendBuf.writerIndex();
            sendBuf.writeBytes(new byte[1]);// 1?Date?
            byte[] keyArray = null;
            byte[] valueArray = null;
            for (Map.Entry<String, Object> param : msg.getHeader().getAttachment().entrySet()) {
                if (param.getValue() instanceof Date) {
                    //Date???byte
                    long time = basedate - ((Date) param.getValue()).getTime();
                    if (time > Integer.MAX_VALUE) {
                        mapDateType.put(param.getKey(), new Long(time));
                    } else if (time > Short.MAX_VALUE) {
                        mapDateType.put(param.getKey(), new Integer((int) time));
                    } else if (time > Byte.MAX_VALUE) {
                        mapDateType.put(param.getKey(), new Short((short) time));
                    } else {
                        mapDateType.put(param.getKey(), new Byte((byte) time));
                    }
                } else if (param.getValue() instanceof String) {
                    //??getBytes()?
                    mapStringType.put(param.getKey(), (String) param.getValue());
                } else {
                    keyArray = param.getKey().getBytes("ISO-8859-1");
                    sendBuf.writeShort(keyArray.length);
                    sendBuf.writeBytes(keyArray);

                    valueArray = serializer.serialize(param.getValue());
                    sendBuf.writeShort(valueArray.length);
                    sendBuf.writeBytes(valueArray);
                }
            }
            sendBuf.setByte(lengthPos,
                    msg.getHeader().getAttachment().size() - mapDateType.size() - mapStringType.size());

            if (mapDateType.isEmpty()) {
                sendBuf.writeByte(0);// 1Date?0
            } else {
                sendBuf.writeByte(mapDateType.size());// 1Date?
                for (Map.Entry<String, Number> param : mapDateType.entrySet()) {
                    keyArray = param.getKey().getBytes("ISO-8859-1");
                    sendBuf.writeShort(keyArray.length);
                    sendBuf.writeBytes(keyArray);

                    if (param.getValue() instanceof Long) {
                        sendBuf.writeByte(8);
                        sendBuf.writeLong((Long) param.getValue());
                    } else if (param.getValue() instanceof Integer) {
                        sendBuf.writeByte(4);
                        sendBuf.writeInt((Integer) param.getValue());
                    } else if (param.getValue() instanceof Short) {
                        sendBuf.writeByte(2);
                        sendBuf.writeShort((Short) param.getValue());
                    } else {
                        sendBuf.writeByte(1);
                        sendBuf.writeByte((Byte) param.getValue());
                    }
                }
            }

            if (mapStringType.isEmpty()) {
                sendBuf.writeByte(0);// 1String?0
            } else {
                sendBuf.writeByte(mapStringType.size());// 1String?
                for (Map.Entry<String, String> param : mapStringType.entrySet()) {
                    keyArray = param.getKey().getBytes("ISO-8859-1");
                    sendBuf.writeShort(keyArray.length);
                    sendBuf.writeBytes(keyArray);

                    valueArray = param.getValue().getBytes("ISO-8859-1");
                    sendBuf.writeShort(valueArray.length);
                    sendBuf.writeBytes(valueArray);
                }
            }
        } else {
            sendBuf.writeByte(0);// 20
        }

        if (msg.getBody() != null) {
            byte[] objArray = serializer.serialize(msg.getBody());
            int lengthPos = sendBuf.writerIndex();
            sendBuf.writeBytes(LENGTH_PLACEHOLDER);// 4Body
            sendBuf.writeBytes(objArray);
            sendBuf.setInt(lengthPos, sendBuf.writerIndex() - lengthPos - 4);// Body
        } else {
            sendBuf.writeInt(0);
        }
        sendBuf.setInt(4, sendBuf.readableBytes() - 8);// Header+Body
    } finally {
        serializePool.restore(serializer);
    }
}

From source file:cubicchunks.network.PacketCubeBlockChange.java

License:MIT License

@SuppressWarnings("deprecation")
@Override//from w  w  w  . ja v  a  2  s.  co m
public void toBytes(ByteBuf out) {
    out.writeInt(cubePos.getX());
    out.writeInt(cubePos.getY());
    out.writeInt(cubePos.getZ());
    out.writeShort(localAddresses.length);
    for (int i = 0; i < localAddresses.length; i++) {
        out.writeShort(localAddresses[i]);
        ByteBufUtils.writeVarInt(out, Block.BLOCK_STATE_IDS.get(blockStates[i]), 4);
    }
    out.writeByte(heightValues.length);
    for (int v : heightValues) {
        out.writeInt(v);
    }
}

From source file:de.gandev.modjn.entity.func.request.WriteMultipleRegistersRequest.java

License:Apache License

@Override
public ByteBuf encode() {
    ByteBuf buf = super.encode();

    buf.writeByte(byteCount);//from   w w w.  ja va2  s  .  c om

    for (int i = 0; i < registers.length; i++) {
        buf.writeShort(registers[i]);
    }

    return buf;
}

From source file:de.gandev.modjn.entity.func.response.ReadHoldingRegistersResponse.java

License:Apache License

@Override
public ByteBuf encode() {
    ByteBuf buf = Unpooled.buffer(calculateLength());
    buf.writeByte(getFunctionCode());/*from  w  w  w.  j  a v a 2s .  com*/
    buf.writeByte(byteCount);

    for (int i = 0; i < registers.length; i++) {
        buf.writeShort(registers[i]);
    }

    return buf;
}