gpt4 book ai didi

php - 如何使用 php 服务器发送 WebSocket hybi-17 帧

转载 作者:搜寻专家 更新时间:2023-10-31 21:14:56 25 4
gpt4 key购买 nike

我尝试在 PHP 握手中实现 WebSocket 服务器,并且接收数据效果很好,但是如果我尝试将数据发送到客户端,Chrome 19 说“服务器不得屏蔽它发送给客户端的任何帧。”但我不掩盖数据。我的代码如下所示:

function wrap($msg=""){ 

$byte1 = 0x80 | (0x1 & 0x0f);

if(strlen($msg) <= 125){
$header = pack('CC', $byte1, strlen($msg));
}
elseif(strlen($msg) >= 126 && strlen($msg) <= 65535){
$header = pack('CCn', $byte1, 126, strlen($msg));
}
else{
$header = pack('CCN', $byte1, 126, strlen($msg));
}
$this->log($header);
return $header.$msg;
}

我使用 socket_write() 将它发送给客户端

编辑:Firefox 13 也关闭了连接

最佳答案

我有同样的问题:对于从服务器发送的一些消息,浏​​览器没有响应,对于一些错误“服务器不能屏蔽任何帧......”显示,虽然我没有添加任何屏蔽.原因在于发送的握手。握手是:

"HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
...
"WebSocket-Location: ws://{$host}{$resource}\r\n\r\n" . chr(0)

那个 chr(0) 是原因,在我删除它之后一切正常。

编码消息的函数:

protected function hybi10Encode($payload, $type = 'text', $masked = true) {
$frameHead = array();
$frame = '';
$payloadLength = strlen($payload);

switch ($type) {
case 'text':
// first byte indicates FIN, Text-Frame (10000001):
$frameHead[0] = 129;
break;

case 'close':
// first byte indicates FIN, Close Frame(10001000):
$frameHead[0] = 136;
break;

case 'ping':
// first byte indicates FIN, Ping frame (10001001):
$frameHead[0] = 137;
break;

case 'pong':
// first byte indicates FIN, Pong frame (10001010):
$frameHead[0] = 138;
break;
}

// set mask and payload length (using 1, 3 or 9 bytes)
if ($payloadLength > 65535) {
$payloadLengthBin = str_split(sprintf('%064b', $payloadLength), 8);
$frameHead[1] = ($masked === true) ? 255 : 127;
for ($i = 0; $i < 8; $i++) {
$frameHead[$i + 2] = bindec($payloadLengthBin[$i]);
}

// most significant bit MUST be 0 (close connection if frame too big)
if ($frameHead[2] > 127) {
$this->close(1004);
return false;
}
} elseif ($payloadLength > 125) {
$payloadLengthBin = str_split(sprintf('%016b', $payloadLength), 8);
$frameHead[1] = ($masked === true) ? 254 : 126;
$frameHead[2] = bindec($payloadLengthBin[0]);
$frameHead[3] = bindec($payloadLengthBin[1]);
} else {
$frameHead[1] = ($masked === true) ? $payloadLength + 128 : $payloadLength;
}

// convert frame-head to string:
foreach (array_keys($frameHead) as $i) {
$frameHead[$i] = chr($frameHead[$i]);
}

if ($masked === true) {
// generate a random mask:
$mask = array();
for ($i = 0; $i < 4; $i++) {
$mask[$i] = chr(rand(0, 255));
}

$frameHead = array_merge($frameHead, $mask);
}
$frame = implode('', $frameHead);
// append payload to frame:
for ($i = 0; $i < $payloadLength; $i++) {
$frame .= ($masked === true) ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
}

return $frame;
}

关于php - 如何使用 php 服务器发送 WebSocket hybi-17 帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11016164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com