Java 类io.netty.channel.DefaultAddressedEnvelope 实例源码

项目:Camel    文件:NettyHelper.java   
/**
 * Writes the given body to Netty channel. Will <b>not</b >wait until the body has been written.
 *
 * @param log             logger to use
 * @param channel         the Netty channel
 * @param remoteAddress   the remote address when using UDP
 * @param body            the body to write (send)
 * @param exchange        the exchange
 * @param listener        listener with work to be executed when the operation is complete
 */
public static void writeBodyAsync(Logger log, Channel channel, SocketAddress remoteAddress, Object body,
                                  Exchange exchange, ChannelFutureListener listener) {
    ChannelFuture future;
    if (remoteAddress != null) {
        if (log.isDebugEnabled()) {
            log.debug("Channel: {} remote address: {} writing body: {}", new Object[]{channel, remoteAddress, body});
        }
        // Need to create AddressedEnvelope to setup the address information here
        DefaultAddressedEnvelope<Object, InetSocketAddress> ae =
            new DefaultAddressedEnvelope<Object, InetSocketAddress>(body, (InetSocketAddress)remoteAddress);
        future = channel.writeAndFlush(ae);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Channel: {} writing body: {}", new Object[]{channel, body});
        }
        // In netty4 we need to call channel flush to send out the message 
        future = channel.writeAndFlush(body);
    }

    if (listener != null) {
        future.addListener(listener);
    }
}
项目:Camel    文件:DatagramPacketByteArrayCodecTest.java   
@Test
public void testDecoder() {
    ByteBuf buf = Unpooled.buffer();
    buf.writeBytes(VALUE.getBytes());
    ByteBuf input = buf.duplicate();
    AddressedEnvelope<Object, InetSocketAddress> addressedEnvelop =
            new DefaultAddressedEnvelope<Object, InetSocketAddress>(input, new InetSocketAddress(8888));
    EmbeddedChannel channel = new EmbeddedChannel(ChannelHandlerFactories.newByteArrayDecoder("udp").newChannelHandler());
    Assert.assertTrue(channel.writeInbound(addressedEnvelop));
    Assert.assertTrue(channel.finish());
    AddressedEnvelope<Object, InetSocketAddress> result = (AddressedEnvelope) channel.readInbound();
    Assert.assertEquals(result.recipient().getPort(), addressedEnvelop.recipient().getPort());
    Assert.assertTrue(result.content() instanceof byte[]);
    Assert.assertEquals(VALUE, new String((byte[]) result.content()));
    Assert.assertNull(channel.readInbound());
}
项目:imflux    文件:UdpDataPacketDecoder.java   
/**
   * Decodes a {@link DatagramPacket} to a {@link DataPacket} wrapped into an {@link AddressedEnvelope} to allow multicast on
   * the used {@link SocketChannel}. 
   * 
   * @param ctx The context of the ChannelHandler
   * @param msg the message which should be encoded
   * @param out a list where all messages are written to
   */
  @Override
  protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {
    final ByteBuf content = msg.content();
final SocketAddress sender = msg.sender();
final SocketAddress recipient = msg.recipient();

      try {
          final DataPacket dataPacket = DataPacket.decode(content);
          final AddressedEnvelope<DataPacket, SocketAddress> newMsg = 
                new DefaultAddressedEnvelope<>(
                        dataPacket, recipient, sender);
        out.add(newMsg);
      } catch (Exception e) {
          LOG.debug("Failed to decode RTP packet.", e);
      }
  }
项目:imflux    文件:UdpControlPacketEncoder.java   
/**
    * Encodes a {@link CompoundControlPacket} wrapped into an {@link AddressedEnvelope} to a {@link ByteBuf} also wrapped
    * into an {@link AddressedEnvelope}. 
    * 
    * @param ctx The context of the ChannelHandler
    * @param msg the message which should be encoded
    * @param out a list where all messages are written to
    */
@Override
protected void encode(ChannelHandlerContext ctx, AddressedEnvelope<CompoundControlPacket, SocketAddress> msg, List<Object> out) throws Exception {
    // encode CompountControlPacket here and forward destination (recipient) of the packet
    final CompoundControlPacket compoundControlPacket = msg.content();
    final List<ControlPacket> packets = compoundControlPacket.getControlPackets();
    ByteBuf compoundBuffer = Unpooled.EMPTY_BUFFER;
    if(!packets.isEmpty()) {
        final ByteBuf[] buffers = new ByteBuf[packets.size()];
        for (int i = 0; i < buffers.length; i++) {
            buffers[i] = packets.get(i).encode();
        }
        compoundBuffer = Unpooled.wrappedBuffer(buffers);
    }

    AddressedEnvelope<ByteBuf, SocketAddress> newMsg = 
            new DefaultAddressedEnvelope<>(compoundBuffer, msg.recipient(), ctx.channel().localAddress());
    out.add(newMsg);
}
项目:imflux    文件:UdpDataPacketEncoder.java   
/**
   * Encodes a {@link DataPacket} wrapped into an {@link AddressedEnvelope} in a {@link ByteBuf} also wrapped into an 
   * {@link AddressedEnvelope}. If the {@link DataPacket}'s content is not empty it is added, otherwise an empty ByteBuf 
   * is added to the AddressedEnvelope.
   * 
   * @param ctx The context of the ChannelHandler
   * @param msg the message which should be encoded
   * @param out a list where all messages are written to
   */
  @Override
  protected void encode(ChannelHandlerContext ctx, AddressedEnvelope<DataPacket, SocketAddress> msg, List<Object> out) throws Exception {
    // encode CompountControlPacket here and forward destination (recipient) of the packet
final DataPacket dataPacket = msg.content();
final SocketAddress recipient = msg.recipient();
final SocketAddress sender = ctx.channel().localAddress();

final ByteBuf buffer;
if (dataPacket.getDataSize() == 0) {
    buffer = Unpooled.EMPTY_BUFFER;
      } else {
        buffer = dataPacket.encode();
      }

final AddressedEnvelope<ByteBuf, SocketAddress> newMsg = 
        new DefaultAddressedEnvelope<>(buffer, recipient, sender);
out.add(newMsg);
  }
项目:Camel    文件:DatagramPacketObjectDecoder.java   
@Override
protected void decode(ChannelHandlerContext ctx, AddressedEnvelope<Object, InetSocketAddress> msg,
                      List<Object> out) throws Exception {
    if (msg.content() instanceof ByteBuf) {
        ByteBuf payload = (ByteBuf) msg.content();
        Object result = delegateDecoder.decode(ctx, payload);
        AddressedEnvelope<Object, InetSocketAddress> addressedEnvelop = 
            new DefaultAddressedEnvelope<Object, InetSocketAddress>(result, msg.recipient(), msg.sender());
        out.add(addressedEnvelop);
    }
}
项目:Camel    文件:DatagramPacketDecoder.java   
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {
    // decode the DatagramPackage to AddressedEnvelope
    DefaultAddressedEnvelope<Object, InetSocketAddress> addressEvelop = 
        new DefaultAddressedEnvelope<Object, InetSocketAddress>(msg.content().retain(), msg.recipient(), msg.sender());
    out.add(addressEvelop);

}
项目:Camel    文件:DatagramPacketObjectEncoder.java   
@Override
protected void encode(ChannelHandlerContext ctx, AddressedEnvelope<Object, InetSocketAddress> msg,
                      List<Object> out) throws Exception {
    if (msg.content() instanceof Serializable) {
        Serializable payload = (Serializable) msg.content();
        ByteBuf buf = ctx.alloc().heapBuffer();
        delegateObjectEncoder.encode(ctx, payload, buf);
        AddressedEnvelope<Object, InetSocketAddress> addressedEnvelop = 
            new DefaultAddressedEnvelope<Object, InetSocketAddress>(buf.retain(), msg.recipient(), msg.sender());
        out.add(addressedEnvelop);
    }

}
项目:Camel    文件:DatagramPacketDelimiterDecoder.java   
@Override
protected void decode(ChannelHandlerContext ctx, AddressedEnvelope<Object, InetSocketAddress> msg,
                      List<Object> out) throws Exception {
    if (msg.content() instanceof ByteBuf) {
        ByteBuf payload = (ByteBuf)msg.content();
        Object result = delegateDecoder.decode(ctx, payload);
        AddressedEnvelope<Object, InetSocketAddress> addressEvelop = 
            new DefaultAddressedEnvelope<Object, InetSocketAddress>(result, msg.recipient(), msg.sender());
        out.add(addressEvelop);
    }

}
项目:Camel    文件:DatagramPacketStringEncoder.java   
@Override
protected void encode(ChannelHandlerContext ctx, AddressedEnvelope<Object, InetSocketAddress> msg,
                      List<Object> out) throws Exception {
    if (msg.content() instanceof CharSequence) {
        CharSequence payload = (CharSequence)msg.content();
        if (payload.length() == 0) {
            return;
        }
        AddressedEnvelope<Object, InetSocketAddress> addressedEnvelop = 
            new DefaultAddressedEnvelope<Object, InetSocketAddress>(ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(payload), charset), msg.recipient(), msg.sender());
        out.add(addressedEnvelop);
    }
}
项目:Camel    文件:DatagramPacketStringDecoder.java   
@Override
protected void decode(ChannelHandlerContext ctx, AddressedEnvelope<Object, InetSocketAddress> msg, List<Object> out) throws Exception {
    if (msg.content() instanceof ByteBuf) {
        ByteBuf payload = (ByteBuf)msg.content();
        AddressedEnvelope<Object, InetSocketAddress> addressedEnvelop = 
            new DefaultAddressedEnvelope<Object, InetSocketAddress>(payload.toString(charset), msg.recipient(), msg.sender());
        out.add(addressedEnvelop);
    }
}
项目:Camel    文件:DatagramPacketByteArrayEncoder.java   
@Override
protected void encode(ChannelHandlerContext ctx, AddressedEnvelope<Object, InetSocketAddress> msg, List<Object> out) throws Exception {
    if (msg.content() instanceof byte[]) {
        delegateEncoder.encode(ctx, (byte[]) msg.content(), out);
        ByteBuf buf = (ByteBuf) out.remove(out.size() - 1);
        AddressedEnvelope<Object, InetSocketAddress> addressedEnvelop = new DefaultAddressedEnvelope<Object, InetSocketAddress>(buf.retain(), msg.recipient(), msg.sender());
        out.add(addressedEnvelop);
    }
}
项目:Camel    文件:DatagramPacketByteArrayCodecTest.java   
@Test
public void testEncoder() {
    ByteBuf buf = Unpooled.buffer();
    buf.writeBytes(VALUE.getBytes());
    AddressedEnvelope<Object, InetSocketAddress> addressedEnvelop =
            new DefaultAddressedEnvelope<Object, InetSocketAddress>(VALUE.getBytes(), new InetSocketAddress(8888));
    EmbeddedChannel channel = new EmbeddedChannel(ChannelHandlerFactories.newByteArrayEncoder("udp").newChannelHandler());
    Assert.assertTrue(channel.writeOutbound(addressedEnvelop));
    Assert.assertTrue(channel.finish());
    AddressedEnvelope output = (AddressedEnvelope) channel.readOutbound();
    Assert.assertTrue(output.content() instanceof ByteBuf);
    ByteBuf resultContent = (ByteBuf) output.content();
    Assert.assertEquals(VALUE, new String(resultContent.array()));
    Assert.assertNull(channel.readOutbound());
}
项目:imflux    文件:UdpControlPacketDecoder.java   
/**
    * Decodes a {@link DatagramPacket} to a {@link CompoundControlPacket} wrapped into an {@link AddressedEnvelope}.
    * 
    * @param ctx The context of the ChannelHandler
    * @param msg the message which should be encoded
    * @param out a list where all messages are written to
    */
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {
    final ByteBuf content = msg.content();
    final SocketAddress sender = msg.sender();
    final SocketAddress recipient = msg.recipient();

    if ((content.readableBytes() % 4) != 0) {
           LOG.debug("Invalid RTCP packet received: total length should be multiple of 4 but is {}",
                content.readableBytes());
           return;
       }

       // Usually 2 packets per UDP frame...
       final List<ControlPacket> controlPacketList = new ArrayList<>(2);

       // While there's data to read, keep on decoding.
       while (content.readableBytes() > 0) {
           try {
            // prevent adding null
            final ControlPacket packet = ControlPacket.decode(content);
            if(packet != null){
                controlPacketList.add(packet);
            }
           } catch (Exception e1) {
               LOG.debug("Exception caught while decoding RTCP packet.", e1);
               break;
           }
       }

       if (!controlPacketList.isEmpty()) {
           // Only forward to next ChannelHandler when there were more than one valid decoded packets.
           // TODO shouldn't the whole compound packet be discarded when one of them has errors?!
        final AddressedEnvelope<CompoundControlPacket, SocketAddress> newMsg = 
                new DefaultAddressedEnvelope<>(new CompoundControlPacket(controlPacketList), recipient, sender);
        out.add(newMsg);
       }
}
项目:netty4study    文件:NioDatagramChannel.java   
@Override
protected boolean doWriteMessage(Object msg, ChannelOutboundBuffer in) throws Exception {
    final Object m;
    final SocketAddress remoteAddress;
    ByteBuf data;
    if (msg instanceof AddressedEnvelope) {
        @SuppressWarnings("unchecked")
        AddressedEnvelope<Object, SocketAddress> envelope = (AddressedEnvelope<Object, SocketAddress>) msg;
        remoteAddress = envelope.recipient();
        m = envelope.content();
    } else {
        m = msg;
        remoteAddress = null;
    }

    if (m instanceof ByteBufHolder) {
        data = ((ByteBufHolder) m).content();
    } else if (m instanceof ByteBuf) {
        data = (ByteBuf) m;
    } else {
        throw new UnsupportedOperationException("unsupported message type: " + StringUtil.simpleClassName(msg));
    }

    int dataLen = data.readableBytes();
    if (dataLen == 0) {
        return true;
    }

    ByteBufAllocator alloc = alloc();
    boolean needsCopy = data.nioBufferCount() != 1;
    if (!needsCopy) {
        if (!data.isDirect() && alloc.isDirectBufferPooled()) {
            needsCopy = true;
        }
    }
    ByteBuffer nioData;
    if (!needsCopy) {
        nioData = data.nioBuffer();
    } else {
        data = alloc.directBuffer(dataLen).writeBytes(data);
        nioData = data.nioBuffer();
    }

    final int writtenBytes;
    if (remoteAddress != null) {
        writtenBytes = javaChannel().send(nioData, remoteAddress);
    } else {
        writtenBytes = javaChannel().write(nioData);
    }

    boolean done =  writtenBytes > 0;
    if (needsCopy) {
        // This means we have allocated a new buffer and need to store it back so we not need to allocate it again
        // later
        if (remoteAddress == null) {
            // remoteAddress is null which means we can handle it as ByteBuf directly
            in.current(data);
        } else {
            if (!done) {
                // store it back with all the needed informations
                in.current(new DefaultAddressedEnvelope<ByteBuf, SocketAddress>(data, remoteAddress));
            } else {
                // Just store back the new create buffer so it is cleaned up once in.remove() is called.
                in.current(data);
            }
        }
    }
    return done;
}
项目:netty-netty-5.0.0.Alpha1    文件:NioDatagramChannel.java   
@Override
protected boolean doWriteMessage(Object msg, ChannelOutboundBuffer in) throws Exception {
    final Object m;
    final SocketAddress remoteAddress;
    ByteBuf data;
    if (msg instanceof AddressedEnvelope) {
        @SuppressWarnings("unchecked")
        AddressedEnvelope<Object, SocketAddress> envelope = (AddressedEnvelope<Object, SocketAddress>) msg;
        remoteAddress = envelope.recipient();
        m = envelope.content();
    } else {
        m = msg;
        remoteAddress = null;
    }

    if (m instanceof ByteBufHolder) {
        data = ((ByteBufHolder) m).content();
    } else if (m instanceof ByteBuf) {
        data = (ByteBuf) m;
    } else {
        throw new UnsupportedOperationException("unsupported message type: " + StringUtil.simpleClassName(msg));
    }

    int dataLen = data.readableBytes();
    if (dataLen == 0) {
        return true;
    }

    ByteBufAllocator alloc = alloc();
    boolean needsCopy = data.nioBufferCount() != 1;
    if (!needsCopy) {
        if (!data.isDirect() && alloc.isDirectBufferPooled()) {
            needsCopy = true;
        }
    }
    ByteBuffer nioData;
    if (!needsCopy) {
        nioData = data.nioBuffer();
    } else {
        data = alloc.directBuffer(dataLen).writeBytes(data);
        nioData = data.nioBuffer();
    }

    final int writtenBytes;
    if (remoteAddress != null) {
        writtenBytes = javaChannel().send(nioData, remoteAddress);
    } else {
        writtenBytes = javaChannel().write(nioData);
    }

    boolean done =  writtenBytes > 0;
    if (needsCopy) {
        // This means we have allocated a new buffer and need to store it back so we not need to allocate it again
        // later
        if (remoteAddress == null) {
            // remoteAddress is null which means we can handle it as ByteBuf directly
            in.current(data);
        } else {
            if (!done) {
                // store it back with all the needed informations
                in.current(new DefaultAddressedEnvelope<ByteBuf, SocketAddress>(data, remoteAddress));
            } else {
                // Just store back the new create buffer so it is cleaned up once in.remove() is called.
                in.current(data);
            }
        }
    }
    return done;
}
项目:imflux    文件:AbstractRtpSession.java   
/**
 * Writes the packets information to the data channel
 * 
 * @param packet
 * @param destination
 */
protected void writeToData(DataPacket packet, SocketAddress destination) {
    final AddressedEnvelope<DataPacket, SocketAddress> envelope = new DefaultAddressedEnvelope<>(packet, destination);
    this.dataChannel.writeAndFlush(envelope);
}
项目:imflux    文件:AbstractRtpSession.java   
/**
 * Write the packets information to the control channel
 * 
 * @param packet
 * @param destination
 */
protected void writeToControl(ControlPacket packet, SocketAddress destination) {
    // FIXME: does not work currently -> add new encoder for ControlPackets wrapped into Envelopes
    final AddressedEnvelope<ControlPacket, SocketAddress> envelope = new DefaultAddressedEnvelope<>(packet, destination);
    this.controlChannel.writeAndFlush(envelope);
}
项目:imflux    文件:AbstractRtpSession.java   
/**
 * Write the packets information to the control channel
 * 
 * @param packet
 * @param destination
 */
protected void writeToControl(CompoundControlPacket packet, SocketAddress destination) {
    final AddressedEnvelope<CompoundControlPacket, SocketAddress> envelope = new DefaultAddressedEnvelope<>(packet, destination);
    this.controlChannel.writeAndFlush(envelope);
}