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); }
private void handleHandshake(ChannelHandlerContext ctx, DatagramPacket packet, int sessionId) { int challengeToken = queryServer.generateChallengeToken(packet.sender()); ByteBuf out = ctx.alloc().buffer(); out.writeByte(ACTION_HANDSHAKE); out.writeInt(sessionId); writeString(out, String.valueOf(challengeToken)); ctx.write(new DatagramPacket(out, packet.sender())); }
/** * Try to add the given {@link DatagramPacket}. Returns {@code true} on success, * {@code false} otherwise. */ boolean add(DatagramPacket packet) { if (count == packets.length) { return false; } ByteBuf content = packet.content(); int len = content.readableBytes(); if (len == 0) { return true; } NativeDatagramPacket p = packets[count]; InetSocketAddress recipient = packet.recipient(); if (!p.init(content, recipient)) { return false; } count++; return true; }
@Override public DatagramPacket replace(ByteBuf content) { return new DatagramPacket(content, recipient(), sender()); }
final RecvByteBufAllocator.Handle allocHandle = unsafe().recvBufAllocHandle(); ByteBuf data = config.getAllocator().heapBuffer(allocHandle.guess()); boolean free = true; try { tmpPacket.setData(data.array(), data.arrayOffset(), data.capacity()); socket.receive(tmpPacket); buf.add(new DatagramPacket(data.writerIndex(allocHandle.lastBytesRead()), localAddress(), remoteAddr)); free = false; return 1;
final ByteBufAllocator allocator = config.getAllocator(); allocHandle.reset(config); readReadyBefore(); do { data = allocHandle.allocate(allocator); allocHandle.attemptedBytesRead(data.writableBytes()); final DatagramSocketAddress remoteAddress; if (data.hasMemoryAddress()) { remoteAddress = socket.recvFromAddress(data.memoryAddress(), data.writerIndex(), data.capacity()); } else { new DatagramPacket(data, (InetSocketAddress) localAddress(), remoteAddress));
@Override protected int doReadMessages(List<Object> buf) throws Exception { DatagramChannel ch = javaChannel(); DatagramChannelConfig config = config(); RecvByteBufAllocator.Handle allocHandle = unsafe().recvBufAllocHandle(); ByteBuf data = allocHandle.allocate(config.getAllocator()); allocHandle.attemptedBytesRead(data.writableBytes()); boolean free = true; try { ByteBuffer nioData = data.internalNioBuffer(data.writerIndex(), data.writableBytes()); int pos = nioData.position(); InetSocketAddress remoteAddress = (InetSocketAddress) ch.receive(nioData); if (remoteAddress == null) { return 0; } allocHandle.lastBytesRead(nioData.position() - pos); buf.add(new DatagramPacket(data.writerIndex(data.writerIndex() + allocHandle.lastBytesRead()), localAddress(), remoteAddress)); free = false; return 1; } catch (Throwable cause) { PlatformDependent.throwException(cause); return -1; } finally { if (free) { data.release(); } } }
@Override public void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out) throws Exception { ByteBuf buf = packet.content(); byte[] encoded = new byte[buf.readableBytes()]; buf.readBytes(encoded); try { Message msg = Message.decode(encoded); DiscoveryEvent event = new DiscoveryEvent(msg, packet.sender()); out.add(event); } catch (Exception e) { throw new RuntimeException("Exception processing inbound message from " + ctx.channel().remoteAddress() + ": " + toHexString(encoded), e); } } }
@Override protected void decode(ChannelHandlerContext ctx, DatagramPacket datagramPacket, List<Object> out) throws Exception { ByteBuf data = datagramPacket.content(); int idx = data.indexOf(0, data.readableBytes(), LogEvent.SEPARATOR); String filename = data.slice(0, idx) .toString(CharsetUtil.UTF_8); String logMsg = data.slice(idx + 1, data.readableBytes()).toString(CharsetUtil.UTF_8); LogEvent event = new LogEvent(datagramPacket.sender(), System.currentTimeMillis(), filename, logMsg); out.add(event); } }
@Override public void broadcast(String subject, byte[] payload) { if (enabled) { Message message = new Message(subject, payload); byte[] bytes = SERIALIZER.encode(message); ByteBuf buf = serverChannel.alloc().buffer(4 + bytes.length); buf.writeInt(bytes.length).writeBytes(bytes); serverChannel.writeAndFlush(new DatagramPacket(buf, groupAddress)); } }
private void handleBasicStats(ChannelHandlerContext ctx, DatagramPacket packet, int sessionId) { GlowServer server = queryServer.getServer(); ByteBuf buf = ctx.alloc().buffer(); buf.writeByte(ACTION_STATS); buf.writeInt(sessionId); writeString(buf, server.getMotd()); writeString(buf, "SMP"); writeString(buf, server.getWorlds().get(0).getName()); writeString(buf, String.valueOf(server.getOnlinePlayers().size())); writeString(buf, String.valueOf(server.getMaxPlayers())); buf.order(ByteOrder.LITTLE_ENDIAN).writeShort(server.getPort()); writeString(buf, getIpString()); ctx.write(new DatagramPacket(buf, packet.sender())); }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { inPackets.incrementAndGet(); if (msg instanceof ByteBuf) { inSize.addAndGet(((ByteBuf) msg).readableBytes()); } else if (msg instanceof DatagramPacket) { inSize.addAndGet(((DatagramPacket) msg).content().readableBytes()); } super.channelRead(ctx, msg); }
@Override protected void encode( ChannelHandlerContext ctx, AddressedEnvelope<DnsQuery, InetSocketAddress> in, List<Object> out) throws Exception { final InetSocketAddress recipient = in.recipient(); final DnsQuery query = in.content(); final ByteBuf buf = allocateBuffer(ctx, in); boolean success = false; try { encodeHeader(query, buf); encodeQuestions(query, buf); encodeRecords(query, DnsSection.ADDITIONAL, buf); success = true; } finally { if (!success) { buf.release(); } } out.add(new DatagramPacket(buf, recipient, null)); }
final ByteBuf data = ((DatagramPacket) msg).content(); if (data.readableBytes() <= 5) { log.debug("Not a valid datagram for processing. Size getTotalRequests needs to be at least more than or equal to 5 bytes. Discarding. (Readable Bytes: {})", data.readableBytes()); return; int protocolHeader = data.readIntLE(); ctx.fireChannelRead(packet.retain()); return; final ByteBuf reassembledPacket = processSplitPackets(data, ctx.channel().alloc(), packet.sender()); ctx.fireChannelRead(packet.replace(reassembledPacket)); return; log.error(String.format("Error while processing packet for %s", ((DatagramPacket) msg).sender()), e); throw e; } finally {
if (msg instanceof DatagramPacket) { DatagramPacket p = (DatagramPacket) msg; ByteBuf content = p.content(); if (isSingleDirectBuffer(content)) { return p; return new DatagramPacket(newDirectBuffer(p, content), p.recipient()); @SuppressWarnings("unchecked") AddressedEnvelope<Object, SocketAddress> e = (AddressedEnvelope<Object, SocketAddress>) msg; if (e.content() instanceof ByteBuf) { ByteBuf content = (ByteBuf) e.content(); if (isSingleDirectBuffer(content)) { return e; return new DefaultAddressedEnvelope<ByteBuf, SocketAddress>(newDirectBuffer(e, content), e.recipient()); "unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES);
@Override protected void decode(final ChannelHandlerContext ctx, final DatagramPacket msg, final List<Object> out) throws Exception { final Session session = this.sessionManager.getSession(msg.sender(), msg.recipient()); final ByteBuf buf = msg.content(); final ByteBuffer headerBuffer = buf.readSlice(Header.SIZE).nioBuffer(); final Header header = new Header(headerBuffer); final ByteBuffer payloadBuffer = buf.readSlice(header.length - Header.SIZE).nioBuffer(); final Packet packet = new Packet(session, msg.sender(), header, payloadBuffer); out.add(new DefaultAddressedEnvelope<>(packet, msg.recipient(), msg.sender())); } }
@Override protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception { // decode the DatagramPackage to AddressedEnvelope DefaultAddressedEnvelope<Object, InetSocketAddress> addressEvelop = new DefaultAddressedEnvelope<>(msg.content().retain(), msg.recipient(), msg.sender()); out.add(addressEvelop); }
@Override protected void encode(ChannelHandlerContext ctx, AddressedEnvelope<Object, InetSocketAddress> msg, List<Object> out) throws Exception { if (msg.content() instanceof ByteBuf) { ByteBuf payload = (ByteBuf)msg.content(); // Just wrap the message as DatagramPacket, need to make sure the message content is ByteBuf DatagramPacket dp = new DatagramPacket(payload.retain(), msg.recipient()); out.add(dp); } else { LOG.debug("Ignoring message content as it is not an io.netty.buffer.ByteBuf instance."); } }