使用 php 将数据推送到 websocket 服务器
Posted
技术标签:
【中文标题】使用 php 将数据推送到 websocket 服务器【英文标题】:Push data to a websocket server with php 【发布时间】:2015-07-24 15:11:46 【问题描述】:我正在尝试将一些数据推送到 websocket 服务器。 握手工作正常,但是当我发送数据时服务器只是忽略它。
我读到数据应该用“\x00”和“\xFF”字符包裹,但我不知道它是否正确。 (试过没有它,但仍然无法正常工作)
这是推送代码:
$host = '127.0.0.1'; //where is the websocket server
$port = 10000;
$origin = "http://localhost/"; //url where this script run
$data = 'server side client message'; //data to be send
$head = "GET / HTTP/1.1\r\n".
"Upgrade: websocket\r\n".
"Connection: Upgrade\r\n".
"Host: $host:$port\r\n".
"Origin: $origin\r\n".
"Sec-WebSocket-Key: k2towQT28s50DtKptTjZbg==\r\n".
"Sec-WebSocket-Version: 13\r\n\r\n";
if($sock = fsockopen($host, $port, $errno, $errstr))
fwrite($sock, $head);
$headers = fread($sock, 2000);
echo nl2br($headers).'<br/><br/>';
echo 'handshake finished<br/>'; //<--- working fine until this point
echo '<br/>sending data: '.$data.'<br/>';
fwrite($sock, "\x00".$data."\xff" ) or die('error:'.$errno.':'.$errstr); //Server ignores this message
//$wsdata = fread($sock, 2000);
//echo '<br/>response: '.trim($wsdata, "\x00\xff").'<br/>';
echo 'closing...';
fclose($sock);
else
echo 'fsockopen failed';
我错过了什么?提前致谢
【问题讨论】:
***.com/a/25740407 你怎么知道服务器忽略了它?您可以访问服务器部分吗?发送标头后服务器返回什么? @JoshTriiJohnston 我正在调试它。该服务器是用 php 编写的,我将消息回显到控制台。我知道它的工作原理,因为我使用 javascript 客户端对其进行了测试。 这里是 github 上的一个 php 库,您可以查看它以了解他们是如何做到的。 github.com/Textalk/websocket-php 它有一个客户端和一个服务器。lib/Client.php
/ lib/Base.php
应该为您提供让您的工作所需的示例。
工作就像一个魅力!谢谢@JoshTriiJohnston
【参考方案1】:
我的修复
<?PHP
$host = '127.0.0.1'; //where is the websocket server
$port = 10000;
$origin = "http://".$host.""; //url where this script run
// Generate the WebSocket key.
$key = generateKey();
//echo 'key: '.$key.'<br>';
$user_name='SERVER';
$user_message=$_GET['msg'];//'server side client message';
$user_color="000000";
$data =json_encode(array('type'=>'usermsg', 'name'=>$user_name, 'message'=>$user_message, 'color'=>$user_color));
$data =hybi10Encode($data);
$head = "GET / HTTP/1.1\r\n".
"Upgrade: websocket\r\n".
"Connection: Upgrade\r\n".
"Host: $host:$port\r\n".
"Origin: $origin\r\n".
"Sec-WebSocket-Key: $key\r\n".
"Sec-WebSocket-Version: 13\r\n\r\n";
if($sock = fsockopen($host, $port, $errno, $errstr))
fwrite($sock, $head);
$header = fread($sock, 2000);
//echo nl2br($header).'<br/><br/>';
//echo 'handshake finished<br/>';
$headers = array();
$lines = preg_split("/\r\n/", $header);
//echo '<br>'.$lines[5].'<br>';
foreach($lines as $line)
$line = chop($line);
if(preg_match('/\A(\S+):(.*)\z/', $line, $matches))
$headers[$matches[1]] = $matches[2];
if($headers['Sec-WebSocket-Accept']===false)
//if (!preg_match('#Sec-WebSocket-Accept:\s(.*)$#mUi', $headers, $matches))
echo "Connection failed: Server sent invalid upgrade response:\n" . $headers.'<br>';
else
//$keyAccept = trim($headers['Sec-WebSocket-Accept']);
$keyAccept = $headers['Sec-WebSocket-Accept'];
//echo 'keyAccept: '.$keyAccept.'<br>';
//echo "Connection succefull: Server sent valid upgrade response:\n" . $keyAccept.'<br>';;
$expectedResonse = base64_encode(pack('H*', sha1($key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
//echo "Connection succefull: Server sent valid upgrade response:\n" . $keyAccept.'<br>';;
if ($keyAccept !== $expectedResonse)
//echo 'Server sent bad upgrade response.'.'<br>';
//echo "ExpectedResonse $expectedResonse".'<br>';
//echo "keyAccept ". $keyAccept.'<br>';
echo 0;
else
echo 1;
//echo 'Server sent correct upgrade response.'.'<br>';
//echo '<br/>sending data: '.$data.'<br/>';
fwrite($sock, $data ) or die('error:'.$errno.':'.$errstr); //Server ignores this message
$wsdata = fread($sock, 2000);
//var_dump(hybi10Decode($wsdata));
//echo 'closing...';
fclose($sock);
else
echo 'fsockopen failed';
/**
* Generate a random string for WebSocket key.
* @return string Random string
*/
function generateKey()
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"$&/()=[]0123456789';
$key = '';
$chars_length = strlen($chars);
for ($i = 0; $i < 16; $i++) $key .= $chars[mt_rand(0, $chars_length-1)];
return base64_encode($key);
function hybi10Decode($data)
$bytes = $data;
$dataLength = '';
$mask = '';
$coded_data = '';
$decodedData = '';
$secondByte = sprintf('%08b', ord($bytes[1]));
$masked = ($secondByte[0] == '1') ? true : false;
$dataLength = ($masked === true) ? ord($bytes[1]) & 127 : ord($bytes[1]);
if($masked === true)
if($dataLength === 126)
$mask = substr($bytes, 4, 4);
$coded_data = substr($bytes, 8);
elseif($dataLength === 127)
$mask = substr($bytes, 10, 4);
$coded_data = substr($bytes, 14);
else
$mask = substr($bytes, 2, 4);
$coded_data = substr($bytes, 6);
for($i = 0; $i < strlen($coded_data); $i++)
$decodedData .= $coded_data[$i] ^ $mask[$i % 4];
else
if($dataLength === 126)
$decodedData = substr($bytes, 4);
elseif($dataLength === 127)
$decodedData = substr($bytes, 10);
else
$decodedData = substr($bytes, 2);
return $decodedData;
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 将数据推送到 websocket 服务器的主要内容,如果未能解决你的问题,请参考以下文章
来自/到 pubsub 和 websocket 的实时转换推送到客户端
Java WebSocket 服务器 - 将消息推送到客户端