我想为 OrientDB 的二进制 API 编写一个 PHP 适配器。
但是我需要一些在 PHP 中具有原始套接字通信经验的人的帮助——我似乎无法克服将 PHP 连接到 OrientDB 的第一个障碍。
如果有人使用套接字来看看这个,我将不胜感激:
http://code.google.com/p/orient/issues/detail?id=126
如果我们能够克服第一个障碍并实际发送一个数据包(该页面底部的简化示例 - 请向下滚动到最后),我当然可以编写适配器。
如果我这样做了,这当然会作为开源发布。
希望有人可以帮助我开始吗?
谢谢!
2010 年 11 月 20 日
参考 PEAR 的 Net_Socket,我最终使用 fsockopen() 和常规 PHP 流函数得到了与我早期尝试的代码基本相同的代码。
我还是一无所获。服务器根本没有反应,即使设置了 5 秒超时,脚本也只是进入深度睡眠,直到超过一般 PHP 脚本时间限制才出来。
这是代码:
<?php
header('Content-type: text/plain');
error_reporting(E_ALL | E_NOTICE | E_WARNING);
$txid = 123;
$db = 'demo';
$username = 'writer';
$password = 'writer';
$packet = "\x05". # 1 byte
pack('i',$txid). # 4 bytes
pack('i',strlen($db)).$db. # string
pack('i',strlen($username)).$username. # string
pack('i',strlen($password)).$password; # string
hex_dump($packet);
$addr = '127.0.0.1';
$port = 2424;
$timeout = 5;
$errstr = '';
$errno = 0;
$socket = fsockopen($addr, $port, $errno, $errstr, $timeout);
stream_set_blocking($socket, 1);
socket_set_timeout($socket, $timeout);
var_dump($socket);
fwrite($socket, $packet);
$response = '';
while (!feof($socket))
$response .= fread($socket, 1024);
hex_dump($response);
fclose($socket);
这是我用来检查我提交的数据包的 hex_dump() 函数:
<?php
function hex_dump($data, $newline="\n")
{
static $from = '';
static $to = '';
static $width = 16; # number of bytes per line
static $pad = '.'; # padding for non-visible characters
if ($from==='')
{
for ($i=0; $i<=0xFF; $i++)
{
$from .= chr($i);
$to .= ($i >= 0x20 && $i <= 0x7E) ? chr($i) : $pad;
}
}
$hex = str_split(bin2hex($data), $width*2);
$chars = str_split(strtr($data, $from, $to), $width);
$offset = 0;
foreach ($hex as $i => $line)
{
echo sprintf('%6X',$offset).' : '.implode(' ', str_split($line,2)) . ' [' . $chars[$i] . ']' . $newline;
$offset += $width;
}
}
根据 OrientDB 的作者 Luca Garulli 的说法,我提交的数据包看起来是正确的。所以还有点不对劲……
这可能是Windows问题吗?我在 Windows 上使用 PHP 5.3,在 Apache 下...