使用 PHP 和 Node.js 的 Websockets [英] Websockets with PHP and Node.js

查看:26
本文介绍了使用 PHP 和 Node.js 的 Websockets的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以让 PHP 脚本通过 websockets 将数据发送到 Node.js 服务器?

Is it possible to have PHP scripts send data through to a Node.js server through websockets?

我正在计划一个附带项目,让 PHP 脚本在后台运行,发挥一些魔法作用,而最终用户将使用的前端应用程序将在 Node.js 中.仅在 Node.js 中会有一些 socket.io 交互,但我希望能够将数据从 PHP 脚本推送到 socket.io.

I'm planning a side project that would have PHP scripts running in the background working some magic and the front end application that end users would use would be in Node.js. There would be some socket.io interaction just in Node.js but I'd like the ability to push data into socket.io from the PHP scripts.

推荐答案

我也在做这个.我的实现与其他实现略有不同.大多数人使用 php &curl + nodejs &快递&套接字

I am also working on this. My implementation is a little different than others. Most people use php & curl + nodejs & express & socketio

我是这样做的:

  • php 和 nodejs 中的 memcache(共享用户 ID 和 cookie)(你也可以使用 redis)
  • 一个自定义 PHP 类,用于通过 websocket 向本地主机发送请求,其中 nodejs 服务器广播到用户房间(来自同一用户的所有会话).

这里是我用来从 php 到 socketio 通信的类(只发送数据到 nodejs 而不是绕过!)

Here is the class I used to communicate from php to socketio (sends only data to nodejs and not the way around!)

当我连接到 socket.io 时,我的脚本读取我的 php cookie 并将其发送到节点服务器,在那里它访问 memcache json 会话并识别用户,将他加入一个房间.

When I connect to socket.io, my script reads my php cookie and sends it to the node server, where it accesses the memcache json sessions and identifies the user, joining him to a room.

这里是一个php json序列化的memcached会话处理程序类.和我用的差不多.

Here is a php json-serialized memcached session handler class. It is similar to the one I used.

要在 php --> socket.io 中发出请求,我执行以下操作:

To make a request in php --> socket.io i do the following:

$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)请求发送到服务器时,我运行以下代码:

When a (socket.io) request from localhost goes to the server, i run this code:

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 代码.像这样:

If i want to pass data from node to php, I simply exec php code on my nodejs server. like this:

 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);
        }
    });
});

这篇关于使用 PHP 和 Node.js 的 Websockets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆