List of usage examples for io.netty.buffer ByteBuf readShort
public abstract short readShort();
From source file:com.tesora.dve.mysqlapi.repl.messages.MyUserVarLogEvent.java
License:Open Source License
String processIntValue(ByteBuf cb, int valueLen) throws PEException { String value = StringUtils.EMPTY; switch (valueLen) { case 8:/* ww w. j a v a 2 s.co m*/ value = Long.toString(cb.readLong()); break; case 7: case 6: case 5: throw new PEException( "Cannot decode INT value of length '" + valueLen + "' for variable '" + variableName + "'"); case 4: value = Long.toString(cb.readInt()); break; case 3: value = Long.toString(cb.readMedium()); break; case 2: value = Long.toString(cb.readShort()); break; case 1: value = Byte.toString(cb.readByte()); break; } return value; }
From source file:com.torchmind.netty.msgpack.codec.MessageCodec.java
License:Apache License
/** * {@inheritDoc}/*from w w w . j a v a 2s . c om*/ */ @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { // read identifier short identifier = in.readShort(); // search message type Class<?> type = this.getRegistry().getMessageType(identifier); // read data byte[] data = new byte[in.readableBytes()]; in.readBytes(data); // decode message out.add(this.messagePack.read(data, type)); }
From source file:com.torchmind.netty.msgpack.test.MessageCodecTest.java
License:Apache License
/** * Tests message encoding.//from w ww. j a va2 s . c o m */ @Test public void encoding() { // create a test message this.channel.writeOutbound(new TestMessage1(42)); this.channel.writeOutbound(new TestMessage2(42, 21)); // verify generated value Assert.assertEquals("Not all messages were encoded", 2, this.channel.outboundMessages().size()); // get first buffer ByteBuf buffer1 = ((ByteBuf) this.channel.outboundMessages().poll()); // verify buffer1 Assert.assertEquals("Packet identifier does not match", 0x00, buffer1.readShort()); Assert.assertEquals("Packet length does not match", 2, buffer1.readableBytes()); // get second buffer ByteBuf buffer2 = ((ByteBuf) this.channel.outboundMessages().poll()); // verify buffer2 Assert.assertEquals("Packet identifier does not match", 0x10, buffer2.readShort()); Assert.assertEquals("Packet length does not match", 3, buffer2.readableBytes()); }
From source file:com.turn.ttorrent.common.protocol.udp.UDPAnnounceRequestMessage.java
License:Apache License
@Override public void fromWire(ByteBuf in) throws MessageValidationException { _fromWire(in, UDP_ANNOUNCE_REQUEST_MESSAGE_SIZE); infoHash = new byte[20]; in.readBytes(infoHash);/*from ww w . j a v a2 s .c o m*/ peerId = new byte[20]; in.readBytes(peerId); downloaded = in.readLong(); uploaded = in.readLong(); left = in.readLong(); event = AnnounceEvent.getById(in.readInt()); if (event == null) throw new MessageValidationException("Invalid event type in announce request!"); InetAddress address; try { byte[] ipBytes = new byte[4]; in.readBytes(ipBytes); address = InetAddress.getByAddress(ipBytes); } catch (UnknownHostException e) { throw new MessageValidationException("Invalid IP address in announce request!", e); } key = in.readInt(); numWant = in.readInt(); int port = in.readShort() & 0xFFFF; peerAddress = new InetSocketAddress(address, port); }
From source file:com.turn.ttorrent.common.protocol.udp.UDPAnnounceResponseMessage.java
License:Apache License
@Override public void fromWire(ByteBuf in) throws MessageValidationException { if (in.readableBytes() < UDP_ANNOUNCE_RESPONSE_MIN_MESSAGE_SIZE || (in.readableBytes() - UDP_ANNOUNCE_RESPONSE_MIN_MESSAGE_SIZE) % 6 != 0) { throw new MessageValidationException("Invalid announce response message size " + in.readableBytes()); }/*from www .jav a 2 s.c o m*/ _fromWire(in, -1); interval = in.readInt(); incomplete = in.readInt(); complete = in.readInt(); peers.clear(); while (in.readableBytes() > 0) { try { byte[] ipBytes = new byte[4]; in.readBytes(ipBytes); InetAddress ip = InetAddress.getByAddress(ipBytes); int port = in.readShort() & 0xFFFF; peers.add(new Peer(new InetSocketAddress(ip, port), null)); } catch (UnknownHostException uhe) { throw new MessageValidationException("Invalid IP address in announce request!"); } } }
From source file:com.vethrfolnir.game.network.mu.MuCyperDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (!in.isReadable()) { MuClient client = ctx.channel().attr(MuClient.ClientKey).get(); _log.warn("Client[" + client + "] sent an empty packet!"); return; //XXX: is it critical? }//from ww w . jav a 2 s. c o m if (in.readableBytes() < 3) { return; // come back later } in.markReaderIndex(); int opcode = in.readUnsignedByte(); int lengthAt = 0; switch (opcode) { case 0xc1: case 0xc3: lengthAt = 1; break; case 0xc2: case 0xc4: lengthAt = 2; break; } //in.markReaderIndex(); int rez = lengthAt > 1 ? in.readShort() : in.readUnsignedByte(); in.resetReaderIndex(); //System.out.println("1 Size[point="+(lengthAt > 1 ? "Short" : "Unsigned byte")+"]: "+rez+" opcode "+Integer.toHexString(opcode & 0xFF)); if (in.readableBytes() < rez) { in.resetReaderIndex(); return; } int header = in.getUnsignedByte(0); if (header == 0xC1 || header == 0xC2) { ByteBuf buff = ctx.alloc().heapBuffer(rez); in.readBytes(buff); out.add(DecodeXor32(buff)); } else { out.add(DecodePacket(in)); } }
From source file:com.weibo.api.motan.transport.netty.NettyDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (in.readableBytes() <= MotanConstants.NETTY_HEADER) { return;/*from www .j av a 2 s. c o m*/ } in.markReaderIndex(); short type = in.readShort(); if (type != MotanConstants.NETTY_MAGIC_TYPE) { in.resetReaderIndex(); throw new MotanFrameworkException("NettyDecoder transport header not support, type: " + type); } byte messageType = (byte) in.readShort(); long requestId = in.readLong(); int dataLength = in.readInt(); // FIXME dataLength? if (in.readableBytes() < dataLength) { in.resetReaderIndex(); return; } if (maxContentLength > 0 && dataLength > maxContentLength) { LoggerUtil.warn( "NettyDecoder transport data content length over of limit, size: {} > {}. remote={} local={}", dataLength, maxContentLength, ctx.channel().remoteAddress(), ctx.channel().localAddress()); Exception e = new MotanServiceException( "NettyDecoder transport data content length over of limit, size: " + dataLength + " > " + maxContentLength); if (messageType == MotanConstants.FLAG_REQUEST) { Response response = buildExceptionResponse(requestId, e); ctx.channel().writeAndFlush(response); throw e; } else { throw e; } } byte[] data = new byte[dataLength]; in.readBytes(data); try { String remoteIp = getRemoteIp(ctx.channel()); out.add(codec.decode(client, remoteIp, data)); } catch (Exception e) { //???? if (messageType == MotanConstants.FLAG_REQUEST) { Response response = buildExceptionResponse(requestId, e); ctx.channel().writeAndFlush(response); return; } else { out.add(buildExceptionResponse(requestId, e)); return; } } }
From source file:com.witjit.game.server.communication.handler.ClientDispatchHandler.java
/** * * @param ctx// w w w .j a v a 2 s. c om * @param msg * @throws Exception */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (!(msg instanceof ByteBuf)) { //TODO: handle error message. return; } ByteBuf mb = (ByteBuf) msg; byte target = mb.readByte(); short id = mb.readShort(); mb.discardReadBytes(); ClientChannelData channelData = ChannelData.get(ctx.channel()); ClientSessionPoint sessionPoint = channelData.getBindSessionPoint(); sessionPoint.transit(target, MessageID.make(id), msg); }
From source file:com.witjit.game.server.communication.netty.handler.NodeChannelInitializer.java
private boolean bindNode(Channel channel, ByteBuf byteBuf) { int bytesCount = byteBuf.readableBytes(); if (bytesCount < 2) { return false; }// w ww . ja v a2s.c om short nodeId = byteBuf.readShort(); ChannelAdapter<M> adapter = new ChannelAdapter<M>(channel); return bindNode(nodeId, adapter); }
From source file:com.yea.remote.netty.codec.NettyMessageDecoder.java
License:Apache License
@Override public Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { ByteBuf frame = (ByteBuf) super.decode(ctx, in); if (frame == null) { return null; }//from w w w .j a va 2 s .c o m ISerializer serializer = serializePool.borrow(); try { Message message = new Message(); byte[] sessionID = new byte[16]; Header header = new Header(); header.setCrcCode(frame.readInt()); header.setLength(frame.readInt()); frame.readBytes(sessionID); header.setSessionID(sessionID); header.setType(frame.readByte()); header.setPriority(frame.readByte()); header.setResult(frame.readByte()); RemoteConstants.CompressionAlgorithm compressionAlgorithm = RemoteConstants.CompressionAlgorithm .valueOf(frame.readByte()); if (compressionAlgorithm != null && compressionAlgorithm.code() > 0) { // serializer.setCompress(new Compress().setCompressionAlgorithm(compressionAlgorithm.algorithm())); } long basedate = frame.readLong(); int attachmentSize = frame.readByte(); if (attachmentSize > 0) { attachmentSize = frame.readByte();//?Date?String? if (attachmentSize > 0) { byte[] keyArray = null; byte[] valueArray = null; for (int i = 0; i < attachmentSize; i++) { keyArray = new byte[frame.readShort()]; frame.readBytes(keyArray); valueArray = new byte[frame.readShort()]; frame.readBytes(valueArray); header.addAttachment(new String(keyArray, "ISO-8859-1"), serializer.deserialize(valueArray)); } } attachmentSize = frame.readByte();//Date? if (attachmentSize > 0) { byte[] keyArray = null; byte length = 0; for (int i = 0; i < attachmentSize; i++) { keyArray = new byte[frame.readShort()]; frame.readBytes(keyArray); length = frame.readByte(); if (length == 1) { header.addAttachment(new String(keyArray, "ISO-8859-1"), new Date(basedate - frame.readByte())); } else if (length == 2) { header.addAttachment(new String(keyArray, "ISO-8859-1"), new Date(basedate - frame.readShort())); } else if (length == 4) { header.addAttachment(new String(keyArray, "ISO-8859-1"), new Date(basedate - frame.readInt())); } else { header.addAttachment(new String(keyArray, "ISO-8859-1"), new Date(basedate - frame.readLong())); } } } attachmentSize = frame.readByte();//String? if (attachmentSize > 0) { byte[] keyArray = null; byte[] valueArray = null; for (int i = 0; i < attachmentSize; i++) { keyArray = new byte[frame.readShort()]; frame.readBytes(keyArray); valueArray = new byte[frame.readShort()]; frame.readBytes(valueArray); header.addAttachment(new String(keyArray, "ISO-8859-1"), new String(valueArray, "ISO-8859-1")); } } } header.addAttachment(NettyConstants.MessageHeaderAttachment.SEND_DATE.value(), new Date(basedate)); header.addAttachment(NettyConstants.MessageHeaderAttachment.RECIEVE_DATE.value(), new Date()); message.setHeader(header); if (frame.readableBytes() > 4) { int length = frame.readInt();//Body byte[] objArray = new byte[length]; frame.readBytes(objArray); try { Object body = serializer.deserialize(objArray); message.setBody(body); } catch (Exception ex) { if (RemoteConstants.MessageType.SERVICE_RESP.value() == message.getHeader().getType()) { message.getHeader().setType(RemoteConstants.MessageType.SUSPEND_RESP.value()); message.getHeader().setResult(RemoteConstants.MessageResult.FAILURE.value()); message.setBody(ex); } else if (RemoteConstants.MessageType.SERVICE_REQ.value() == message.getHeader().getType()) { message.getHeader().setType(RemoteConstants.MessageType.SUSPEND_REQ.value()); message.getHeader().setResult(RemoteConstants.MessageResult.FAILURE.value()); message.setBody(ex); } else { throw ex; } } } return message; } finally { serializePool.restore(serializer); frame.release(); } }