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?
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献