Websocket - 客户端不接收数据 [英] Websocket - client doesn't receive data

查看:66
本文介绍了Websocket - 客户端不接收数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些基于 websockets (RFC 6455) 的应用程序.不幸的是,客户端(在 Chrome 18 上测试)似乎没有收到数据,但服务器说它正在发送......

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 什么也没说

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));
}

推荐答案

如果您发送的测试消息大于 125 字节但 <65536,则您的问题可能是由要打包的错误格式字符串引起的.我认为这个应该是'CCn'(您当前的代码以错误的顺序写入长度的2个字节).

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:

  • onopen 回调是否运行以证明初始握手成功完成?
  • onerror 或 onclose 回调是否在连接后或服务器发送消息后运行?

这篇关于Websocket - 客户端不接收数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆