我也在做这个。
我的实现与其他实现略有不同。
大多数人使用 php & curl + nodejs & express & socketio
我是通过以下方式完成的:
- php和nodejs中的memcache(共享userid和cookie)(也可以使用redis)
- 一个自定义 PHP 类,用于通过 websocket 向 localhost 发送请求,其中 nodejs 服务器向用户房间广播(来自同一用户的所有会话)。
Here 是我用来从 php 到 socketio 通信的类(只向 nodejs 发送数据,而不是反过来!)
当我连接到 socket.io 时,我的脚本读取我的 php cookie 并将其发送到节点服务器,在那里它访问 memcache json 会话并识别用户,将他加入一个房间。
Here 是一个 php json 序列化的 memcached 会话处理程序类。和我用的差不多。
要在 php --> socket.io 中发出请求,我执行以下操作:
$s = new SocketIO('127.0.0.1', 8088);
$adata = "On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain.";
$msg = json_encode(array('event'=> 'passdata','data'=> $adata, 'to'=> 1));
$tr = 0;
$fl = 0;
for ($i = 0 ; $i < 1000; $i++) {
$s->send( 'broadcast', $msg ) ? $tr++ : $fl++;
}
echo "HIT : " . $tr . PHP_EOL;
echo "MISS: " . $fl;
当来自 localhost 的 (socket.io) 请求发送到服务器时,我运行以下代码:
var is_local = (this_ip === '127.0.0.1' ? true : false);
socket.on('broadcast', function(data) {
if (data.length === 0 ) return;
if (is_local && typeof data === 'string') {
try {
var j = JSON.parse(data);
} catch (e) {
console.log("invalid json @ broadcast".red);
return false;
}
if (!j.hasOwnProperty('to') && !j.hasOwnProperty('event')) return false;
io.to(j.to).emit(j.event, j.data);
console.log('brc'.blue + ' to: ' + j.to + ' evt: ' + j.event);
/** @todo remove disconnect & try to create permanent connection */
socket.disconnect();
} else { console.log('brc ' + 'error'.red ); }
});
如果我想将数据从节点传递到 php,我只需在我的 nodejs 服务器上执行 php 代码。
像这样:
socket.on('php', function(func, data, callback) {
/* some functions */
if (check_usr(session) === false) return;
console.log('php'.green + ' act:' + func);
var cmd = 'php -r \'$_COOKIE["MONSTER"]="' + session + '"; require(\"' + __dirname + '/' + php_[func].exec + '\");\'';
console.log(cmd);
cp.exec(cmd ,
function(err, stdout, stderr) {
if (err == null) {
console.log(typeof callback);
console.log(JSON.parse(callback));
if (callback != null) callback(stdout);
console.log(stdout);
//socket.emit('php', {uid: uid, o: stdout});
console.log('emitted');
} else {
console.log('err '.red + stdout + ' ' + stderr);
}
});
});