io.netty.channel.socket.DatagramPacket#content ( )源码实例Demo

下面列出了io.netty.channel.socket.DatagramPacket#content ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: netty-4.1.22   文件: DatagramDnsResponseDecoder.java
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out) throws Exception {
    final ByteBuf buf = packet.content();

    final DnsResponse response = newResponse(packet, buf);
    boolean success = false;
    try {
        final int questionCount = buf.readUnsignedShort();
        final int answerCount = buf.readUnsignedShort();
        final int authorityRecordCount = buf.readUnsignedShort();
        final int additionalRecordCount = buf.readUnsignedShort();

        decodeQuestions(response, buf, questionCount);
        decodeRecords(response, DnsSection.ANSWER, buf, answerCount);
        decodeRecords(response, DnsSection.AUTHORITY, buf, authorityRecordCount);
        decodeRecords(response, DnsSection.ADDITIONAL, buf, additionalRecordCount);

        out.add(response);
        success = true;
    } finally {
        if (!success) {
            response.release();
        }
    }
}
 
源代码2 项目: netty-4.1.22   文件: DatagramDnsQueryDecoder.java
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out) throws Exception {
    final ByteBuf buf = packet.content();

    final DnsQuery query = newQuery(packet, buf);
    boolean success = false;
    try {
        final int questionCount = buf.readUnsignedShort();
        final int answerCount = buf.readUnsignedShort();
        final int authorityRecordCount = buf.readUnsignedShort();
        final int additionalRecordCount = buf.readUnsignedShort();

        decodeQuestions(query, buf, questionCount);
        decodeRecords(query, DnsSection.ANSWER, buf, answerCount);
        decodeRecords(query, DnsSection.AUTHORITY, buf, authorityRecordCount);
        decodeRecords(query, DnsSection.ADDITIONAL, buf, additionalRecordCount);

        out.add(query);
        success = true;
    } finally {
        if (!success) {
            query.release();
        }
    }
}
 
源代码3 项目: dfactor   文件: KcpTestClient.java
@Override
		protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket pack) throws Exception {
			final ByteBuf buf = pack.content();
			final int size = buf.readableBytes();
			if(size > 0){
				int connId = 0;
				if(buf.readByte()==Kcp.FLAG && size > 1 + 4){ //valid kcp head
					connId = buf.getInt(buf.readerIndex());
				}
				if(connId > 0){ //valid kcp pack
					pack.retain();
					queueRecv.offer(pack);
//					log.I("Recv kcp pack, sender="+pack.sender().toString());
				}else{  //normal udp pack
					log.I("Recv udp pack, sender="+pack.sender().toString());
				}
			}else{
				log.E("Invalid pack, len=0, sender="+pack.sender().toString());
			}
		}
 
源代码4 项目: gsc-core   文件: PacketDecoder.java
@Override
public void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out)
        throws Exception {
    ByteBuf buf = packet.content();
    int length = buf.readableBytes();
    if (length <= 1 || length >= MAXSIZE) {
        logger
                .error("UDP rcv bad packet, from {} length = {}", ctx.channel().remoteAddress(), length);
        return;
    }
    byte[] encoded = new byte[length];
    buf.readBytes(encoded);
    try {
        UdpEvent event = new UdpEvent(Message.parse(encoded), packet.sender());
        out.add(event);
    } catch (Exception e) {
        logger.error("Parse msg failed, type {}, len {}, address {}", encoded[0], encoded.length,
                packet.sender());
    }
}
 
源代码5 项目: java-Kcp   文件: Crc32Decode.java
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof DatagramPacket) {
        DatagramPacket datagramPacket = (DatagramPacket) msg;
        ByteBuf data = datagramPacket.content();
        long checksum =  data.readUnsignedIntLE();
        ByteBuffer byteBuffer = data.nioBuffer(data.readerIndex(),data.readableBytes());
        crc32.reset();
        crc32.update(byteBuffer);
        if(checksum!=crc32.getValue()){
            Snmp.snmp.getInCsumErrors().increment();
            return;
        }
    }
   ctx.fireChannelRead(msg);
}
 
源代码6 项目: arcusplatform   文件: IrisUpnpServer.java
@Override
public void channelRead(@Nullable ChannelHandlerContext ctx, @Nullable Object msg) throws Exception {
   DatagramPacket packet = (DatagramPacket)msg;
   if (packet == null) {
      return;
   }

   try {
      ByteBuf content = packet.content();
      if (log.isTraceEnabled()) {
         log.trace("recv upnp message: {}", content.toString(StandardCharsets.UTF_8));
      }

      if (content.readableBytes() > 5 &&
          content.getByte(content.readerIndex()) == 'H' &&
          content.getByte(content.readerIndex()+1) == 'T' &&
          content.getByte(content.readerIndex()+2) == 'T' &&
          content.getByte(content.readerIndex()+3) == 'P' &&
          content.getByte(content.readerIndex()+4) == '/') {
         handleResponse(ctx, packet);
      } else {
         handleRequest(ctx, packet);
      }
   } catch (Throwable th) {
      log.debug("error processing upnp packet:", th);
   } finally {
      if (packet.refCnt() > 0) {
         packet.release(packet.refCnt());
      }
   }
}
 
源代码7 项目: onos   文件: LispMessageDecoder.java
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket msg,
                      List<Object> list) throws Exception {
    ByteBuf byteBuf = msg.content();
    LispMessageReader reader = LispMessageReaderFactory.getReader(byteBuf);
    LispMessage message = (LispMessage) reader.readFrom(byteBuf);
    message.configSender(msg.sender());
    list.add(message);
}
 
源代码8 项目: riiablo   文件: ReliableChannelHandler.java
protected void messageReceived(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
  InetSocketAddress sender = packet.sender();
  Gdx.app.log(TAG, "messageReceived received packet from " + sender.getHostName() + ":" + sender.getPort());
  ByteBuf in = packet.content();
  if (DEBUG_INBOUND) Gdx.app.debug(TAG, "  " + ByteBufUtil.hexDump(in));
  endpoint.messageReceived(ctx, packet.sender(), packet);
}
 
源代码9 项目: ffwd   文件: DatagramPacketToByteBuf.java
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out)
    throws Exception {
    final ByteBuf buf = packet.content();
    buf.retain();
    out.add(buf);
}
 
源代码10 项目: AgentX   文件: Udp2TcpHandler.java
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    DatagramPacket datagram = (DatagramPacket) msg;
    InetSocketAddress sender = datagram.sender();
    Channel tcpChannel = XChannelMapper.getTcpChannel(sender);
    if (tcpChannel == null) {
        // udpSource not registered, actively discard this packet
        // without register, an udp channel cannot relate to any tcp channel, so remove the map
        XChannelMapper.removeUdpMapping(sender);
        log.warn("Bad Connection! (unexpected udp datagram from {})", sender);
    } else if (tcpChannel.isActive()) {
        ByteBuf byteBuf = datagram.content();
        try {
            if (!byteBuf.hasArray()) {
                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.getBytes(0, bytes);
                log.info("\t          Proxy << Target \tFrom   {}:{}", sender.getHostString(), sender.getPort());

                // write udp payload via tcp channel
                tcpChannel.writeAndFlush(Unpooled.wrappedBuffer(wrapper.wrap(requestResolver.wrap(XRequest.Channel.UDP, bytes))));
                log.info("\tClient << Proxy           \tGet [{} bytes]", bytes.length);
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}
 
@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
    ByteBuf data = msg.content();
    if (data.readableBytes() > 6 && data.readIntLE() == -1) {
        byte[] raw = new byte[data.readableBytes() - 2];
        data.readBytes(raw);
        data.skipBytes(2);
        //Pass to the callback
        if (logEventCallback != null)
            logEventCallback.accept(new SourceLogEntry(new String(raw, Charsets.UTF_8), msg.sender()));
    }
}
 
源代码12 项目: c5-replicator   文件: UdpProtostuffDecoder.java
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket dgram, List<Object> out) throws Exception {
  ByteBuf msg = dgram.content();

  ByteBufferInput input = new ByteBufferInput(msg.nioBuffer(), protostuffEncoded);
  T newMsg = schema.newMessage();
  schema.mergeFrom(input, newMsg);
  out.add(newMsg);
}
 
源代码13 项目: mpush   文件: PacketDecoder.java
public static Packet decodeFrame(DatagramPacket frame) {
    ByteBuf in = frame.content();
    int readableBytes = in.readableBytes();
    int bodyLength = in.readInt();
    if (readableBytes < (bodyLength + Packet.HEADER_LEN)) {
        return null;
    }

    return decodePacket(new UDPPacket(in.readByte()
            , frame.sender()), in, bodyLength);
}
 
源代码14 项目: Geyser   文件: ConnectorServerEventHandler.java
@Override
public void onUnhandledDatagram(ChannelHandlerContext ctx, DatagramPacket packet) {
    new QueryPacketHandler(connector, packet.sender(), packet.content());
}
 
源代码15 项目: Nemisys   文件: SessionManager.java
private boolean receivePacket() throws Exception {
    DatagramPacket datagramPacket = this.socket.readPacket();
    if (datagramPacket != null) {
        ByteBuf byteBuf = datagramPacket.content();
        byte[] buffer = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(buffer);
        byteBuf.release();
        int len = buffer.length;
        String source = datagramPacket.sender().getHostString();
        currentSource = source; //in order to block address
        int port = datagramPacket.sender().getPort();
        if (len > 0) {
            this.receiveBytes += len;
            if (this.block.containsKey(source)) {
                return true;
            }

            if (this.ipSec.containsKey(source)) {
                this.ipSec.put(source, this.ipSec.get(source) + 1);
            } else {
                this.ipSec.put(source, 1);
            }

            byte pid = buffer[0];

            if (pid == UNCONNECTED_PONG.ID) {
                return false;
            }

            Packet packet = this.getPacketFromPool(pid);
            if (packet != null) {
                packet.buffer = buffer;
                this.getSession(source, port).handlePacket(packet);
                return true;
            } else if (pid == UNCONNECTED_PING.ID) {
                packet = new UNCONNECTED_PING();
                packet.buffer = buffer;
                packet.decode();

                UNCONNECTED_PONG pk = new UNCONNECTED_PONG();
                pk.serverID = this.getID();
                pk.pingID = ((UNCONNECTED_PING) packet).pingID;
                pk.serverName = this.getName();
                this.sendPacket(pk, source, port);
            } else if (buffer.length != 0) {
                this.streamRAW(source, port, buffer);
                return true;
            } else {
                return false;
            }
        }
    }

    return false;
}
 
源代码16 项目: timely   文件: UdpPacketToByteBuf.java
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {
    ByteBuf buf = msg.content();
    buf.retain();
    out.add(buf);
}
 
源代码17 项目: Nukkit   文件: SessionManager.java
private boolean receivePacket() throws Exception {
    DatagramPacket datagramPacket = this.socket.readPacket();
    if (datagramPacket != null) {
        // Check this early
        try {
            String source = datagramPacket.sender().getHostString();
            currentSource = source; //in order to block address
            if (this.block.containsKey(source)) {
                return true;
            }

            if (this.ipSec.containsKey(source)) {
                this.ipSec.put(source, this.ipSec.get(source) + 1);
            } else {
                this.ipSec.put(source, 1);
            }

            ByteBuf byteBuf = datagramPacket.content();
            if (byteBuf.readableBytes() == 0) {
                // Exit early to process another packet
                return true;
            }
            byte[] buffer = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(buffer);
            int len = buffer.length;
            int port = datagramPacket.sender().getPort();

            this.receiveBytes += len;

            byte pid = buffer[0];

            if (pid == UNCONNECTED_PONG.ID) {
                return false;
            }

            Packet packet = this.getPacketFromPool(pid);
            if (packet != null) {
                packet.buffer = buffer;
                this.getSession(source, port).handlePacket(packet);
                return true;
            } else if (pid == UNCONNECTED_PING.ID) {
                packet = new UNCONNECTED_PING();
                packet.buffer = buffer;
                packet.decode();

                UNCONNECTED_PONG pk = new UNCONNECTED_PONG();
                pk.serverID = this.getID();
                pk.pingID = ((UNCONNECTED_PING) packet).pingID;
                pk.serverName = this.getName();
                this.sendPacket(pk, source, port);
            } else if (buffer.length != 0) {
                this.streamRAW(source, port, buffer);
                return true;
            } else {
                return false;
            }
        } finally {
            datagramPacket.release();
        }
    }

    return false;
}
 
源代码18 项目: plog   文件: ProtocolDecoder.java
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out)
        throws Exception {
    final ByteBuf content = msg.content();
    final byte versionIdentifier = content.getByte(0);
    // versions are non-printable characters, push down the pipeline send as-is.
    if (versionIdentifier < 0 || versionIdentifier > 31) {
        log.debug("Unboxed UDP message");
        stats.receivedUdpSimpleMessage();
        msg.retain();
        out.add(new MessageImpl(content, null));
    } else if (versionIdentifier == 0) {
        final byte typeIdentifier = content.getByte(1);
        switch (typeIdentifier) {
            case 0:
                final FourLetterCommand cmd = readCommand(msg);
                if (cmd != null) {
                    log.debug("v0 command");
                    out.add(cmd);
                } else {
                    stats.receivedUnknownCommand();
                }
                break;
            case 1:
                log.debug("v0 multipart message: {}", msg);
                try {
                    final Fragment fragment = Fragment.fromDatagram(msg);
                    stats.receivedV0MultipartFragment(fragment.getFragmentIndex());
                    msg.retain();
                    out.add(fragment);
                } catch (IllegalArgumentException e) {
                    log.error("Invalid header", e);
                    stats.receivedV0InvalidMultipartHeader();
                }
                break;
            default:
                stats.receivedV0InvalidType();
        }
    } else {
        stats.receivedUdpInvalidVersion();
    }
}
 
源代码19 项目: Jupiter   文件: SessionManager.java
private boolean receivePacket() throws Exception {
    DatagramPacket datagramPacket = this.socket.readPacket();
    if (datagramPacket != null) {
        // Check this early
        try {
            String source = datagramPacket.sender().getHostString();
            currentSource = source; //in order to block address
            if (this.block.containsKey(source)) {
                return true;
            }

            if (this.ipSec.containsKey(source)) {
                this.ipSec.put(source, this.ipSec.get(source) + 1);
            } else {
                this.ipSec.put(source, 1);
            }

            ByteBuf byteBuf = datagramPacket.content();
            if (byteBuf.readableBytes() == 0) {
                // Exit early to process another packet
                return true;
            }
            byte[] buffer = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(buffer);
            int len = buffer.length;
            int port = datagramPacket.sender().getPort();

            this.receiveBytes += len;

            byte pid = buffer[0];

            if (pid == UNCONNECTED_PONG.ID) {
                return false;
            }

            Packet packet = this.getPacketFromPool(pid);
            if (packet != null) {
                packet.buffer = buffer;
                this.getSession(source, port).handlePacket(packet);
                return true;
            } else if (pid == UNCONNECTED_PING.ID) {
                packet = new UNCONNECTED_PING();
                packet.buffer = buffer;
                packet.decode();

                UNCONNECTED_PONG pk = new UNCONNECTED_PONG();
                pk.serverID = this.getID();
                pk.pingID = ((UNCONNECTED_PING) packet).pingID;
                pk.serverName = this.getName();
                this.sendPacket(pk, source, port);
            } else if (buffer.length != 0) {
                this.streamRAW(source, port, buffer);
                return true;
            } else {
                return false;
            }
        } finally {
            datagramPacket.release();
        }
    }

    return false;
}
 
源代码20 项目: JRakNet   文件: Packet.java
/**
 * Creates packet from an existing {@link DatagramPacket}.
 * 
 * @param datagram
 *            the {@link DatagramPacket} to read from.
 */
public Packet(DatagramPacket datagram) {
	this(datagram.content());
}