Search in sources :

Example 21 with ByteBufOutputStream

use of org.apache.flink.shaded.netty4.io.netty.buffer.ByteBufOutputStream in project netty-socketio by mrniko.

the class PacketEncoder method encodePacket.

public void encodePacket(Packet packet, ByteBuf buffer, ByteBufAllocator allocator, boolean binary) throws IOException {
    ByteBuf buf = buffer;
    if (!binary) {
        buf = allocateBuffer(allocator);
    }
    byte type = toChar(packet.getType().getValue());
    buf.writeByte(type);
    try {
        switch(packet.getType()) {
            case PONG:
                {
                    buf.writeBytes(packet.getData().toString().getBytes(CharsetUtil.UTF_8));
                    break;
                }
            case OPEN:
                {
                    ByteBufOutputStream out = new ByteBufOutputStream(buf);
                    jsonSupport.writeValue(out, packet.getData());
                    break;
                }
            case MESSAGE:
                {
                    ByteBuf encBuf = null;
                    if (packet.getSubType() == PacketType.ERROR) {
                        encBuf = allocateBuffer(allocator);
                        ByteBufOutputStream out = new ByteBufOutputStream(encBuf);
                        jsonSupport.writeValue(out, packet.getData());
                    }
                    if (packet.getSubType() == PacketType.EVENT || packet.getSubType() == PacketType.ACK) {
                        List<Object> values = new ArrayList<Object>();
                        if (packet.getSubType() == PacketType.EVENT) {
                            values.add(packet.getName());
                        }
                        encBuf = allocateBuffer(allocator);
                        List<Object> args = packet.getData();
                        values.addAll(args);
                        ByteBufOutputStream out = new ByteBufOutputStream(encBuf);
                        jsonSupport.writeValue(out, values);
                        if (!jsonSupport.getArrays().isEmpty()) {
                            packet.initAttachments(jsonSupport.getArrays().size());
                            for (byte[] array : jsonSupport.getArrays()) {
                                packet.addAttachment(Unpooled.wrappedBuffer(array));
                            }
                            packet.setSubType(packet.getSubType() == PacketType.ACK ? PacketType.BINARY_ACK : PacketType.BINARY_EVENT);
                        }
                    }
                    byte subType = toChar(packet.getSubType().getValue());
                    buf.writeByte(subType);
                    if (packet.hasAttachments()) {
                        byte[] ackId = toChars(packet.getAttachments().size());
                        buf.writeBytes(ackId);
                        buf.writeByte('-');
                    }
                    if (packet.getSubType() == PacketType.CONNECT) {
                        if (!packet.getNsp().isEmpty()) {
                            buf.writeBytes(packet.getNsp().getBytes(CharsetUtil.UTF_8));
                        }
                    } else {
                        if (!packet.getNsp().isEmpty()) {
                            buf.writeBytes(packet.getNsp().getBytes(CharsetUtil.UTF_8));
                            buf.writeByte(',');
                        }
                    }
                    if (packet.getAckId() != null) {
                        byte[] ackId = toChars(packet.getAckId());
                        buf.writeBytes(ackId);
                    }
                    if (encBuf != null) {
                        buf.writeBytes(encBuf);
                        encBuf.release();
                    }
                    break;
                }
        }
    } finally {
        // we need to write a buffer in any case
        if (!binary) {
            buffer.writeByte(0);
            int length = buf.writerIndex();
            buffer.writeBytes(longToBytes(length));
            buffer.writeByte(0xff);
            buffer.writeBytes(buf);
            buf.release();
        }
    }
}
Also used : ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) List(java.util.List) ArrayList(java.util.ArrayList) ByteBuf(io.netty.buffer.ByteBuf)

Example 22 with ByteBufOutputStream

use of org.apache.flink.shaded.netty4.io.netty.buffer.ByteBufOutputStream in project netty by netty.

the class CompatibleObjectEncoder method encode.

@Override
protected void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception {
    // Suppress a warning about resource leak since oss is closed below
    ObjectOutputStream oos = newObjectOutputStream(// lgtm[java/output-resource-leak]
    new ByteBufOutputStream(out));
    try {
        if (resetInterval != 0) {
            // Resetting will prevent OOM on the receiving side.
            writtenObjects++;
            if (writtenObjects % resetInterval == 0) {
                oos.reset();
            }
        }
        oos.writeObject(msg);
        oos.flush();
    } finally {
        oos.close();
    }
}
Also used : ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) ObjectOutputStream(java.io.ObjectOutputStream)

Example 23 with ByteBufOutputStream

use of org.apache.flink.shaded.netty4.io.netty.buffer.ByteBufOutputStream in project netty by netty.

the class Http2StreamChannelIdTest method testSerialization.

@Test
public void testSerialization() throws Exception {
    ChannelId normalInstance = new Http2StreamChannelId(DefaultChannelId.newInstance(), 0);
    ByteBuf buf = Unpooled.buffer();
    ObjectOutputStream outStream = new ObjectOutputStream(new ByteBufOutputStream(buf));
    try {
        outStream.writeObject(normalInstance);
    } finally {
        outStream.close();
    }
    ObjectInputStream inStream = new ObjectInputStream(new ByteBufInputStream(buf, true));
    final ChannelId deserializedInstance;
    try {
        deserializedInstance = (ChannelId) inStream.readObject();
    } finally {
        inStream.close();
    }
    assertEquals(normalInstance, deserializedInstance);
    assertEquals(normalInstance.hashCode(), deserializedInstance.hashCode());
    assertEquals(0, normalInstance.compareTo(deserializedInstance));
    assertEquals(normalInstance.asLongText(), deserializedInstance.asLongText());
    assertEquals(normalInstance.asShortText(), deserializedInstance.asShortText());
}
Also used : ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) ByteBufInputStream(io.netty.buffer.ByteBufInputStream) DefaultChannelId(io.netty.channel.DefaultChannelId) ChannelId(io.netty.channel.ChannelId) ByteBuf(io.netty.buffer.ByteBuf) ObjectOutputStream(java.io.ObjectOutputStream) ObjectInputStream(java.io.ObjectInputStream) Test(org.junit.jupiter.api.Test)

Example 24 with ByteBufOutputStream

use of org.apache.flink.shaded.netty4.io.netty.buffer.ByteBufOutputStream in project netty by netty.

the class DefaultChannelIdTest method testSerialization.

@Test
public void testSerialization() throws Exception {
    ChannelId a = DefaultChannelId.newInstance();
    ChannelId b;
    ByteBuf buf = Unpooled.buffer();
    ObjectOutputStream out = new ObjectOutputStream(new ByteBufOutputStream(buf));
    try {
        out.writeObject(a);
        out.flush();
    } finally {
        out.close();
    }
    ObjectInputStream in = new ObjectInputStream(new ByteBufInputStream(buf, true));
    try {
        b = (ChannelId) in.readObject();
    } finally {
        in.close();
    }
    assertThat(a, is(b));
    assertThat(a, is(not(sameInstance(b))));
    assertThat(a.asLongText(), is(b.asLongText()));
}
Also used : ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) ByteBufInputStream(io.netty.buffer.ByteBufInputStream) ByteBuf(io.netty.buffer.ByteBuf) ObjectOutputStream(java.io.ObjectOutputStream) ObjectInputStream(java.io.ObjectInputStream) Test(org.junit.jupiter.api.Test)

Example 25 with ByteBufOutputStream

use of org.apache.flink.shaded.netty4.io.netty.buffer.ByteBufOutputStream in project netty by netty.

the class PcapWriteHandlerTest method udpV4.

@Test
public void udpV4() throws InterruptedException {
    ByteBuf byteBuf = Unpooled.buffer();
    InetSocketAddress srvReqAddr = new InetSocketAddress("127.0.0.1", 0);
    InetSocketAddress cltReqAddr = new InetSocketAddress("127.0.0.1", 0);
    NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(2);
    // We'll bootstrap a UDP Server to avoid "Network Unreachable errors" when sending UDP Packet.
    Bootstrap server = new Bootstrap().group(eventLoopGroup).channel(NioDatagramChannel.class).handler(new SimpleChannelInboundHandler<DatagramPacket>() {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) {
        // Discard
        }
    });
    ChannelFuture channelFutureServer = server.bind(srvReqAddr).sync();
    assertTrue(channelFutureServer.isSuccess());
    // We'll bootstrap a UDP Client for sending UDP Packets to UDP Server.
    Bootstrap client = new Bootstrap().group(eventLoopGroup).channel(NioDatagramChannel.class).handler(new PcapWriteHandler(new ByteBufOutputStream(byteBuf)));
    ChannelFuture channelFutureClient = client.connect(channelFutureServer.channel().localAddress(), cltReqAddr).sync();
    assertTrue(channelFutureClient.isSuccess());
    Channel clientChannel = channelFutureClient.channel();
    assertTrue(clientChannel.writeAndFlush(Unpooled.wrappedBuffer("Meow".getBytes())).sync().isSuccess());
    assertTrue(eventLoopGroup.shutdownGracefully().sync().isSuccess());
    // Verify Pcap Global Headers
    verifyGlobalHeaders(byteBuf);
    // Verify Pcap Packet Header
    // Just read, we don't care about timestamps for now
    byteBuf.readInt();
    // Just read, we don't care about timestamps for now
    byteBuf.readInt();
    // Length of Packet Saved In Pcap
    assertEquals(46, byteBuf.readInt());
    // Actual Length of Packet
    assertEquals(46, byteBuf.readInt());
    // -------------------------------------------- Verify Packet --------------------------------------------
    // Verify Ethernet Packet
    ByteBuf ethernetPacket = byteBuf.readBytes(46);
    ByteBuf dstMac = ethernetPacket.readBytes(6);
    ByteBuf srcMac = ethernetPacket.readBytes(6);
    assertArrayEquals(new byte[] { 0, 0, 94, 0, 83, -1 }, ByteBufUtil.getBytes(dstMac));
    assertArrayEquals(new byte[] { 0, 0, 94, 0, 83, 0 }, ByteBufUtil.getBytes(srcMac));
    assertEquals(0x0800, ethernetPacket.readShort());
    // Verify IPv4 Packet
    ByteBuf ipv4Packet = ethernetPacket.readBytes(32);
    // Version + IHL
    assertEquals(0x45, ipv4Packet.readByte());
    // DSCP
    assertEquals(0x00, ipv4Packet.readByte());
    // Length
    assertEquals(32, ipv4Packet.readShort());
    // Identification
    assertEquals(0x0000, ipv4Packet.readShort());
    // Fragment
    assertEquals(0x0000, ipv4Packet.readShort());
    // TTL
    assertEquals((byte) 0xff, ipv4Packet.readByte());
    // Protocol
    assertEquals((byte) 17, ipv4Packet.readByte());
    // Checksum
    assertEquals(0, ipv4Packet.readShort());
    InetSocketAddress localAddr = (InetSocketAddress) clientChannel.remoteAddress();
    // Source IPv4 Address
    assertEquals(NetUtil.ipv4AddressToInt((Inet4Address) localAddr.getAddress()), ipv4Packet.readInt());
    InetSocketAddress remoteAddr = (InetSocketAddress) clientChannel.localAddress();
    // Destination IPv4 Address
    assertEquals(NetUtil.ipv4AddressToInt((Inet4Address) remoteAddr.getAddress()), ipv4Packet.readInt());
    // Verify UDP Packet
    ByteBuf udpPacket = ipv4Packet.readBytes(12);
    // Source Port
    assertEquals(remoteAddr.getPort() & 0xffff, udpPacket.readUnsignedShort());
    // Destination Port
    assertEquals(localAddr.getPort() & 0xffff, udpPacket.readUnsignedShort());
    // Length
    assertEquals(12, udpPacket.readShort());
    // Checksum
    assertEquals(0x0001, udpPacket.readShort());
    // Verify Payload
    ByteBuf payload = udpPacket.readBytes(4);
    // Payload
    assertArrayEquals("Meow".getBytes(CharsetUtil.UTF_8), ByteBufUtil.getBytes(payload));
    // Release all ByteBuf
    assertTrue(dstMac.release());
    assertTrue(srcMac.release());
    assertTrue(payload.release());
    assertTrue(byteBuf.release());
    assertTrue(ethernetPacket.release());
    assertTrue(ipv4Packet.release());
    assertTrue(udpPacket.release());
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Inet4Address(java.net.Inet4Address) ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) InetSocketAddress(java.net.InetSocketAddress) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) DatagramPacket(io.netty.channel.socket.DatagramPacket) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.jupiter.api.Test)

Aggregations

ByteBufOutputStream (io.netty.buffer.ByteBufOutputStream)52 ByteBuf (io.netty.buffer.ByteBuf)37 IOException (java.io.IOException)18 ObjectOutputStream (java.io.ObjectOutputStream)11 OutputStreamWriter (java.io.OutputStreamWriter)6 ByteBufInputStream (io.netty.buffer.ByteBufInputStream)5 OutputStream (java.io.OutputStream)5 Test (org.junit.jupiter.api.Test)5 ObjectInputStream (java.io.ObjectInputStream)4 SneakyThrows (lombok.SneakyThrows)4 NBTTagCompound (net.minecraft.nbt.NBTTagCompound)4 ByteBufAllocator (io.netty.buffer.ByteBufAllocator)3 Writer (java.io.Writer)3 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 CodedOutputStream (com.google.protobuf.CodedOutputStream)2 Bootstrap (io.netty.bootstrap.Bootstrap)2 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)2