是否可以让PHP脚本通过websockets将数据发送到Node.js服务器?
我正在计划一个将在后台运行PHP脚本并运行一些魔术的最终项目,而最终用户将使用的前端应用程序将在Node.js中.仅在Node.js中会有一些socket.io交互,但我希望能够从PHP脚本将数据推送到socket.io.
解决方法:
我也在做这个.
我的实现与其他实现略有不同.
大多数人使用PHP& curl nodejs&表达与socketio
我已经通过以下方式做到了:
> PHP和nodejs中的内存缓存(共享用户名和cookie)(您也可以使用redis)
>一个自定义PHP类,可通过websocket向本地主机发送请求,在该主机上,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;
当来自本地主机的(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 ); }
});
如果我想将数据从node传递到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);
}
});
});