Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Custom Packet with Compression  (Read 2096 times)

0 Members and 1 Guest are viewing this topic.

Bernhard

  • Newbie
  • *
  • Posts: 3
    • View Profile
Custom Packet with Compression
« on: July 20, 2015, 06:02:44 pm »
Hi everyone,

I'm trying to use custom Packets with the TcpSocket class so that I can have automatic compression/decompression using Google's "Snappy" library. I'm having some difficulties with it though, and it seems that for some reason the "onReceive" function isn't firing on the receiver. Here is my custom packet:

class CustomPacket : public sf::Packet
{
        virtual const void* onSend(std::size_t& size)
        {
                const void* srcData = getData();
                std::size_t srcSize = getDataSize();
                // allocate space for compressed data
                size_t compressedLength = snappy_max_compressed_length(sizeof((const char*)srcData));
                char *compressed = new char[compressedLength];
                // compress the data
                snappy_status status = snappy_compress((const char*)srcData, srcSize, compressed, &size);
                return (const void*)compressed;
        }
        virtual void onReceive(const void* data, std::size_t size)
        {
                printf("Receiving...");
                size_t uncompressedLength;
                snappy_status status = snappy_uncompressed_length(
                        (const char*)data, size, &uncompressedLength);
                char *uncompressed = new char[uncompressedLength];
                std::size_t dstSize;
                status = snappy_uncompress(
                        (const char*)data, size, uncompressed, &dstSize);
                append((const void*)uncompressed, dstSize);
        }
};

On the sender, this is what I'm doing:

CustomPacket packet;
std::string s = "test message please ignore";
packet << s;
sf::Socket::Status status = socket.send(packet);

And on the receiver:

CustomPacket packet;
if (client.receive(packet) == sf::Socket::Done)
{
        std::string s;
        packet >> s;
        printf("Packet received: %s", s.c_str());
}

If I get rid of the compression algorithm in onSend, it works fine and prints out "Packet received: test message please ignore". With the compression in it though, as above, it prints out "Packet received: ", without any message.

Any ideas on why the custom packet isn't working properly?
« Last Edit: July 20, 2015, 06:08:55 pm by Bernhard »