Я пытаюсь подключиться к socket.io серверу через прокси-сервер с помощью PHP, но получаю некорректный ответ (ниже заголовки, которые я получаю в ответ):
HTTP/1.1 400 Bad Request
Content-Type: application/json
Access-Control-Allow-Origin: *
Date: Mon, 06 Nov 2017 18:10:46 GMT
Connection: Close
Proxy-Connection: Close
{"code":3,"message":"Bad request"}
Мой код:
<?php
ob_implicit_flush();
function generateKey($length = 16) {
$c = 0;
$tmp = '';
while ($c++ * 16 < $length) {
$tmp .= md5(mt_rand(), true);
}
return base64_encode(substr($tmp, 0, $length));
}
function hybi10Encode($payload, $type = 'text', $masked = true)
{
$frameHead = array();
$payloadLength = strlen($payload);
switch ($type) {
case 'text':
$frameHead[0] = 129;
break;
case 'close':
$frameHead[0] = 136;
break;
case 'ping':
$frameHead[0] = 137;
break;
case 'pong':
$frameHead[0] = 138;
break;
}
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]);
}
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;
}
foreach (array_keys($frameHead) as $i) {
$frameHead[$i] = chr($frameHead[$i]);
}
if ($masked === true) {
$mask = array();
for ($i = 0; $i < 4; $i++) {
$mask[$i] = chr(rand(0, 255));
}
$frameHead = array_merge($frameHead, $mask);
}
$frame = implode('', $frameHead);
for ($i = 0; $i < $payloadLength; $i++) {
$frame .= ($masked === true) ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
}
return $frame;
}
$protocol = "http://";
$host = "myip";
$port = "myhost";
$path = "/socket.io/?EIO=2&transport=websocket";
$proxy = explode("@", "proxyip:proxyport@proxyusr:proxypwd");
$proxy_host = explode(":", $proxy[0]);
$proxy_auth = base64_encode($proxy[1]);
$key = generateKey();
$socket = fsockopen($proxy_host[0], $proxy_host[1]);
$headers = "GET {$protocol}{$host}:{$port}{$path} HTTP/1.1\r\n";
$headers.= "Host: {$proxy[0]}\r\n";
$headers.= "Proxy-Authorization: Basic {$proxy_auth}\r\n";
$headers.= "Proxy-Connection: Keep-Alive\r\n";
$headers.= "Upgrade: WebSocket\r\n";
$headers.= "Connection: Upgrade\r\n";
$headers.= "Sec-WebSocket-Key: $key\r\n";
$headers.= "Sec-WebSocket-Version: 13\r\n";
$headers.= "Origin: *\r\n\r\n";
fwrite($socket, $headers);
$result = fread($socket, 10000);
print_r($result);
while (!feof($socket)) {
$data = fgets($socket, 128);
fwrite($socket, hybi10Encode('42["action",{"action":1}]'));
}
fclose($socket);
?>