我在服务器端使用PHP套接字,在客户端使用JavaScript套接字。握手,取消屏蔽和屏蔽对于长度不超过125的消息正常工作,但是问题是,当服务器发送的数据超过125个字节时,客户端套接字不会接收到数据并自动关闭。
这是我正在使用的代码:
private function unmask($payload) {
$length = ord($payload[1]) & 127;
if($length == 126) {
$masks = substr($payload, 4, 4);
$data = substr($payload, 8);
$len = (ord($payload[2]) << 8) + ord($payload[3]);
}
elseif($length == 127) {
$masks = substr($payload, 10, 4);
$data = substr($payload, 14);
$len = (ord($payload[2]) << 56) + (ord($payload[3]) << 48) + (ord($payload[4]) << 40) + (ord($payload[5]) << 32) + (ord($payload[6]) << 24) + (ord($payload[7]) << 16) + (ord($payload[8]) << 8) + ord($payload[9]);
}
else {
$masks = substr($payload, 2, 4);
$data = substr($payload, 6);
$len = $length;
}
$text = '';
for ($i = 0; $i < $len; ++$i) {
$text .= $data[$i] ^ $masks[$i%4];
}
return $text;
}
private function 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);
elseif($length >= 65536)
$header = pack('CCN', $b1, 127, $length);
return $header.$text;
}
private function handshake($buffer,$socket,$socket_index) {
list($resource,$host,$origin,$key) = $this->getSocketKeyFromHeaders($buffer);
$retkey = base64_encode(sha1($key."258EAFA5-E914-47DA-95CA-C5AB0DC85B11",true));
$upgrade = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: {$retkey}\r\n\r\n";
$this->handshakes[$socket_index] = true;
socket_write($socket,$upgrade,strlen($upgrade));
echo $this->output("Done handshaking...\n");
}
private function getSocketKeyFromHeaders($req) {
$req = substr($req,4); /* RegEx kill babies */
$res = substr($req,0,strpos($req," HTTP"));
$req = substr($req,strpos($req,"Host:")+6);
$host = substr($req,0,strpos($req,"\r\n"));
$req = substr($req,strpos($req,"Sec-WebSocket-Key: ")+19);
$key = trim(substr($req,0,strpos($req,"\r\n")));
$req = substr($req,strpos($req,"Origin:")+8);
$ori = substr($req,0,strpos($req,"\r\n"));
return array($res,$host,$ori,$key);
}