douyun1546 2012-05-29 18:57
浏览 234
已采纳

Websocket - 客户端不接收数据

I'm writing some app based on websockets (RFC 6455). Unfortunetly it looks like the client (testing on Chrome 18) doesn't receive data, but the server says it is sending...

Chrome doesn't say anything

Here are main server methods:

private function decode($payload) {
    $length = ord($payload[1]) & 127;

    if ($length == 126) {
        $masks = substr($payload, 4, 4);
        $data = substr($payload, 8);
    } elseif ($length == 127) {
        $masks = substr($payload, 10, 4);
        $data = substr($payload, 14);
    } else {
        $masks = substr($payload, 2, 4);
        $data = substr($payload, 6);
    }

    $text = '';
    for ($i = 0; $i < strlen($data); ++$i) {
        $text .= $data[$i] ^ $masks[$i % 4];
    }

    $text = base64_decode($text);
    return $text;
}

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

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

    return $header . $text;
} 

protected function process($user, $msg) {
    echo '<< '.$msg.N;
    if (empty($msg)) {
        $this->send($user->socket, $msg);
        return;
    }
}

protected function send($client, $msg) {
    $msg = $this->encode($msg);
    echo '>> '.$msg.N;
    socket_write($client, $msg, strlen($msg));
}
  • 写回答

1条回答 默认 最新

  • dongsuoying9059 2012-05-30 09:26
    关注

    If you're sending a test message >125 bytes but <65536, your problem might be caused by a faulty format string to pack. I think this one should be 'CCn' (your current code writes the 2 bytes of the length in the wrong order).

    If that doesn't help, you could try some client-side logging:

    • Does the onopen callback run to prove that the initial handshake completed successfully?
    • Do the onerror or onclose callbacks run, either after connection or after your server sends its message?
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?