Search code examples
socketsnetwork-programmingudppacketsendto

how can i split an instance of my packet class into chunks and send them with socket_sendto function?


I have packet like this

    class Packet {
            private $DATASize;
            private $signature;
            private $version;
            private $HSIZE;
            private $SessionIDUser1;
            private $SessionIDUser2;
           }

I'm using UDP protocol.


Solution

  • Since there is no methods in this class, you can encode the instance with json_encode and send him as a string. on the client side just decode and clone. it can be done also when the class have methods, with more complication.

    Example:

    //server
    $p = new Packet;
    socket_sendto($sock, json_encode($p), strlen($p), 0, $ip, $port);
    
    //client
    socket_recvfrom($sock, $buf, $size, 0, $ip, $port);
    $p = clone json_decode($bof); //class without methods
    $p = new Packet;
    $p->setAs(json_decode($bof) ); //class with methods: implement this method too.
    

    Edit:

    Now i see that your fields are private, so you need implement method for json encoding. see https://stackoverflow.com/a/7005915/2075420 and https://stackoverflow.com/a/9942303/2075420.