Dharman
Dharman

Reputation: 33238

Websockets encoding data to be send

I'm trying to encode the data that I will send to the browser using websockets. I base myself on this tutorial:

private function encode($text) {
    // 0x1 text frame (FIN + opcode)
    $b1 = 0x80 | (0x1 & 0x0f);
    $length = strlen($text);

    if($length > 125 && $length < 65536)
        $header = pack('CCS', $b1, 126, $length);
    elseif($length >= 65536)
        $header = pack('CCN', $b1, 127, $length);

    return $header.$text;
}

Can anyone tell me what's wrong with this function because I'm not getting any data in web browser.
I use it on this line:

    $msg = $this->encode($msg);

    parent::send($client,$msg);

PS: I'm not good with binary actions.

Upvotes: 1

Views: 2601

Answers (3)

HartleySan
HartleySan

Reputation: 7810

I used that same code originally to encode data in my WebSocket script, and it won't work in some cases even with your corrections. The problem is that the length of the payload (data) is not properly calculated. In other words, you can't just use the strlen function.

Please see my related post for details on how to fix this: What is this data at the end of WebRTC candidate info?

Upvotes: 1

Brandon
Brandon

Reputation: 176

Dharman's corrected if statements fail for strings over 125 characters. The correct if statements are:

    if($length <= 125) {
        $header = pack('CC', $b1, $length);
    } elseif ($length > 125 && $length < 65536) {
        $header = pack('CSC', $b1, 126, $length);
    } elseif ($length >= 65536) {
        $header = pack('CNC', $b1, 127, $length);
    }

Upvotes: 2

Dharman
Dharman

Reputation: 33238

I solved it. The if statements were wrong. That's how they should look like:

    if($length <= 125)
        $header = pack('CC', $b1, $length);
    elseif($length > 125 && $length < 65536)
        $header = pack('CCS', $b1, 126, $length);
    elseif($length >= 65536)
        $header = pack('CCN', $b1, 127, $length);

Upvotes: 1

Related Questions