PHP socket strange characters when sending data fast

Viewed 63

I used this chat PHP app with sockets: https://phppot.com/php/simple-php-chat-using-websocket/

But when I'm sending data really fast:

for (let i = 0; i < 50; i++) {
    websocket.send(JSON.stringify({ action: 'testtesttest' }));
}

I got strange characters like:

)›Ñ?‹[gÀV1“ÂHÈ™]a„“]g‹ÌpÈ’\`‹Úch‹Ž)‹Mw‹Ìg‹Úc"…Ò ôh‹Ž)‹”PfÇ„]a‹Ìg‹ÚcNÔÌC1ÇÂ1Ä•\1…ÂL1“» ?›ÌNÔ½EYÞ 

They say PHP websocket | strange characters when sending data with high frequency that it has something todo with the unmask method:

function unseal($socketData) {
        $length = ord($socketData[1]) & 127;
        if($length == 126) {
            $masks = substr($socketData, 4, 4);
            $data = substr($socketData, 8);
        }
        elseif($length == 127) {
            $masks = substr($socketData, 10, 4);
            $data = substr($socketData, 14);
        }
        else {
            $masks = substr($socketData, 2, 4);
            $data = substr($socketData, 6);
        }
        $socketData = "";
        for ($i = 0; $i < strlen($data); ++$i) {
            $socketData .= $data[$i] ^ $masks[$i%4];
        }
        return $socketData;
    }

But I don't know what.

Can someone help me out?

1 Answers

This has caught me out before. The issue is caused by more than one frame being sent by the client within the same TCP packet. This is done by the client for efficiency reasons.

In your unseal function, you are getting the $length variable, but never using it. To resolve the issue, truncate the $data variable by $length bytes, then use the remaining bytes to call the unseal function again.

This recursive calling will mean your unseal function might return more than one message - so you probably want it to return an array of strings.

EDIT: I typed up my findings here: https://github.com/g105b/text (and for fun, deployed the application at https://www.walloftext.art)

Related