如何集成nodeJS + Socket。IO和PHP吗?

时间:2022-08-22 16:32:31

I have recently been looking around, to find a good way to communicate between nodeJS and PHP. Here is the idea : nodeJS is still quite new, and it can be kind of tricky to develop a full application only with it. Moreover, you may need it only for one module of your project, like realtime notifications, chat, ... And you want to manage all the other stuff with PHP, because it is probably more easy for you (and you can take advantage of the existing frameworks, like CodeIgniter or Symfony).

我最近一直在寻找一种在node - js和PHP之间进行交流的好方法。这里的想法是:nodeJS仍然是相当新的,仅用它开发完整的应用程序可能有点棘手。此外,您可能只需要它用于项目的一个模块,比如实时通知、聊天、……您还希望使用PHP管理所有其他内容,因为这对您来说可能更容易(并且您可以利用现有的框架,比如CodeIgniter或Symfony)。

I would like to have an easy solution ; I don't want to use cURL, or a third server to communicate between Apache and Node servers. What I want is to be able to catch events from node in simple Javascript, client-side.

我希望有一个简单的解决方案;我不希望使用cURL或第三方服务器在Apache和节点服务器之间进行通信。我想要的是能够用简单的Javascript,客户端捕获节点的事件。

I didn't find any answers that where complete, most of the time client-side was running by the node server and so not applicable in my case. So I crawled all the possible topics, and finally find my answer ; I'll try to share this, and to have a point where it's all clear.

我没有找到任何答案,在完成时,客户端大部分时间是由节点服务器运行的,因此在我的例子中不适用。于是我爬了所有可能的话题,终于找到了答案;我会试着和大家分享这个,并且要有一个清晰的观点。

Hope this can help some people ! ;)

希望这能对一些人有所帮助!,)

2 个解决方案

#1


124  

So, to begin with, I put my project on github, if you want access to the full code : https://github.com/jdutheil/nodePHP

因此,首先,如果您想访问完整的代码:https://github.com/jdutheil/nodePHP,我将我的项目放在github上

It is a very simple example project : a web chat. You just have an author and message, and when you press send it is saved in a mysql database. The idea is to send real time updates, and have a real conversation. ;) We'll use nodeJS for that.

这是一个非常简单的示例项目:web聊天。您只有一个作者和消息,当您按下send时,它被保存在mysql数据库中。我们的想法是发送实时更新,进行真正的对话。,)我们会用nodeJS。

I won't talk about PHP code, it is really simple and not interesting here ; what I want to show you is how to integrate your nodeJS code.

我不会讲PHP代码,这里很简单,也不有趣;我想向您展示的是如何集成nodeJS代码。

I use express and Socket.IO, so be sure to install those modules with npm. Then, we create a simple nodeJS server :

我使用express和Socket。IO,所以一定要在npm中安装这些模块。然后,我们创建一个简单的nodeJS服务器:

var socket = require( 'socket.io' );
var express = require( 'express' );
var http = require( 'http' );

var app = express();
var server = http.createServer( app );

var io = socket.listen( server );

io.sockets.on( 'connection', function( client ) {
    console.log( "New client !" );

    client.on( 'message', function( data ) {
        console.log( 'Message received ' + data.name + ":" + data.message );

        io.sockets.emit( 'message', { name: data.name, message: data.message } );
    });
});

server.listen( 8080 );

We registered our events callback when a new user is connected ; every time we receive a message (represents a chat message), we broadcast it to every users connected. Now, the tricky part : client-side ! That the part that took me most of the time, because I didn't know wich script include to be able to run Socket.IO code without the nodeServer (because client page will be served by Apache). But everything is already done ; when you install Socket.IO module with npm, a script is available in /node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js ; that the script we will include in our PHP page, in my case :

当新用户连接时,我们注册了事件回调;每当我们收到一条消息(代表一条聊天消息)时,我们就把它广播给所有连接的用户。现在,棘手的部分是:客户端!那部分我花了大部分时间,因为我不知道维奇脚本包括能够运行套接字。没有nodeServer的IO代码(因为客户端页面将由Apache提供)。但一切都已完成;当你安装插座。使用npm的IO模块,可以在/node_modules/socket.io/node_modules/socket.io . client/dist/socket.io中使用脚本。js;我们将在PHP页面中包含的脚本,在我的例子中:

    <script src="js/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js"></script>
    <script src="js/nodeClient.js"></script>

And to finish, my nodeClient.js, where we simply connect to the node server and wait for event to update our page. ;)

最后,我的朋友。我们只需连接到节点服务器并等待事件更新页面。,)

var socket = io.connect( 'http://localhost:8080' );

$( "#messageForm" ).submit( function() {
    var nameVal = $( "#nameInput" ).val();
    var msg = $( "#messageInput" ).val();

    socket.emit( 'message', { name: nameVal, message: msg } );

    // Ajax call for saving datas
    $.ajax({
        url: "./ajax/insertNewMessage.php",
        type: "POST",
        data: { name: nameVal, message: msg },
        success: function(data) {

        }
    });

    return false;
});

socket.on( 'message', function( data ) {
    var actualContent = $( "#messages" ).html();
    var newMsgContent = '<li> <strong>' + data.name + '</strong> : ' + data.message + '</li>';
    var content = newMsgContent + actualContent;

    $( "#messages" ).html( content );
});

I'll try to update and improve my code as soon as possible, but I think it already open to all of cool things ! I am really open for advice and reviews on this stuff, is it the good way to do it, .. ?

我将尽快更新和改进我的代码,但是我认为它已经向所有的酷东西开放了!对于这件事我很愿意听听你的意见和意见,你看这是不是个好办法。吗?

Hope this can help some people !

希望这能帮助一些人!

#2


2  

I have another solution that works quite well for me, but I would like someone to comment about how effective it is, as I have not (yet) had the opportunity/time to test it on the real server.

我有另一个解决方案,对我来说很好,但是我希望有人评论它的有效性,因为我还没有机会/时间在真正的服务器上测试它。

Here goes the node-js code. I put this code in a file called nodeserver.js:

这是node-js代码。我把这段代码放在一个名为nodeserver.js的文件中:

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});

    var knall = new Object();
    knall.totten = "4 tomtar";
    knall.theArr = new Array();
    knall.theArr.push("hoppla")
    knall.theArr.push("hej")
    var strKnall = JSON.stringify(knall);

    res.end(strKnall);
}).listen(process.env.PORT);  

And here is the simple piece of code in php, calling the node-js server with the help of file_get_contents():

下面是php中的一段简单的代码,在file_get_contents()的帮助下调用node-js服务器:

$json = file_get_contents('http://localhost:3002/knall.json');
$obj = json_decode($json);

Works great, when I load the php-page, it in turn calls the nodeserver.js page, which jsonify the knall-object.

当我加载php页面时,它会调用nodeserver。js页面,它将knall对象jsonify。

I have two localhost-installations running on iis on windows 10, one standard php-server, and the nodejs-server works with the neat iisnode package.

我在windows 10上有两个运行在iis上的本地主机安装,一个标准的php-server, nodejs-server与整洁的iisnode包一起工作。

The 'real' server is run on ubuntu.

真正的服务器是在ubuntu上运行的。

I think this is a neat and easy solution for communication between two servers, but maybe someone has any comments about it?

我认为对于两个服务器之间的通信来说,这是一个简洁而容易的解决方案,但是也许有人对此有什么看法?

#1


124  

So, to begin with, I put my project on github, if you want access to the full code : https://github.com/jdutheil/nodePHP

因此,首先,如果您想访问完整的代码:https://github.com/jdutheil/nodePHP,我将我的项目放在github上

It is a very simple example project : a web chat. You just have an author and message, and when you press send it is saved in a mysql database. The idea is to send real time updates, and have a real conversation. ;) We'll use nodeJS for that.

这是一个非常简单的示例项目:web聊天。您只有一个作者和消息,当您按下send时,它被保存在mysql数据库中。我们的想法是发送实时更新,进行真正的对话。,)我们会用nodeJS。

I won't talk about PHP code, it is really simple and not interesting here ; what I want to show you is how to integrate your nodeJS code.

我不会讲PHP代码,这里很简单,也不有趣;我想向您展示的是如何集成nodeJS代码。

I use express and Socket.IO, so be sure to install those modules with npm. Then, we create a simple nodeJS server :

我使用express和Socket。IO,所以一定要在npm中安装这些模块。然后,我们创建一个简单的nodeJS服务器:

var socket = require( 'socket.io' );
var express = require( 'express' );
var http = require( 'http' );

var app = express();
var server = http.createServer( app );

var io = socket.listen( server );

io.sockets.on( 'connection', function( client ) {
    console.log( "New client !" );

    client.on( 'message', function( data ) {
        console.log( 'Message received ' + data.name + ":" + data.message );

        io.sockets.emit( 'message', { name: data.name, message: data.message } );
    });
});

server.listen( 8080 );

We registered our events callback when a new user is connected ; every time we receive a message (represents a chat message), we broadcast it to every users connected. Now, the tricky part : client-side ! That the part that took me most of the time, because I didn't know wich script include to be able to run Socket.IO code without the nodeServer (because client page will be served by Apache). But everything is already done ; when you install Socket.IO module with npm, a script is available in /node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js ; that the script we will include in our PHP page, in my case :

当新用户连接时,我们注册了事件回调;每当我们收到一条消息(代表一条聊天消息)时,我们就把它广播给所有连接的用户。现在,棘手的部分是:客户端!那部分我花了大部分时间,因为我不知道维奇脚本包括能够运行套接字。没有nodeServer的IO代码(因为客户端页面将由Apache提供)。但一切都已完成;当你安装插座。使用npm的IO模块,可以在/node_modules/socket.io/node_modules/socket.io . client/dist/socket.io中使用脚本。js;我们将在PHP页面中包含的脚本,在我的例子中:

    <script src="js/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js"></script>
    <script src="js/nodeClient.js"></script>

And to finish, my nodeClient.js, where we simply connect to the node server and wait for event to update our page. ;)

最后,我的朋友。我们只需连接到节点服务器并等待事件更新页面。,)

var socket = io.connect( 'http://localhost:8080' );

$( "#messageForm" ).submit( function() {
    var nameVal = $( "#nameInput" ).val();
    var msg = $( "#messageInput" ).val();

    socket.emit( 'message', { name: nameVal, message: msg } );

    // Ajax call for saving datas
    $.ajax({
        url: "./ajax/insertNewMessage.php",
        type: "POST",
        data: { name: nameVal, message: msg },
        success: function(data) {

        }
    });

    return false;
});

socket.on( 'message', function( data ) {
    var actualContent = $( "#messages" ).html();
    var newMsgContent = '<li> <strong>' + data.name + '</strong> : ' + data.message + '</li>';
    var content = newMsgContent + actualContent;

    $( "#messages" ).html( content );
});

I'll try to update and improve my code as soon as possible, but I think it already open to all of cool things ! I am really open for advice and reviews on this stuff, is it the good way to do it, .. ?

我将尽快更新和改进我的代码,但是我认为它已经向所有的酷东西开放了!对于这件事我很愿意听听你的意见和意见,你看这是不是个好办法。吗?

Hope this can help some people !

希望这能帮助一些人!

#2


2  

I have another solution that works quite well for me, but I would like someone to comment about how effective it is, as I have not (yet) had the opportunity/time to test it on the real server.

我有另一个解决方案,对我来说很好,但是我希望有人评论它的有效性,因为我还没有机会/时间在真正的服务器上测试它。

Here goes the node-js code. I put this code in a file called nodeserver.js:

这是node-js代码。我把这段代码放在一个名为nodeserver.js的文件中:

var http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});

    var knall = new Object();
    knall.totten = "4 tomtar";
    knall.theArr = new Array();
    knall.theArr.push("hoppla")
    knall.theArr.push("hej")
    var strKnall = JSON.stringify(knall);

    res.end(strKnall);
}).listen(process.env.PORT);  

And here is the simple piece of code in php, calling the node-js server with the help of file_get_contents():

下面是php中的一段简单的代码,在file_get_contents()的帮助下调用node-js服务器:

$json = file_get_contents('http://localhost:3002/knall.json');
$obj = json_decode($json);

Works great, when I load the php-page, it in turn calls the nodeserver.js page, which jsonify the knall-object.

当我加载php页面时,它会调用nodeserver。js页面,它将knall对象jsonify。

I have two localhost-installations running on iis on windows 10, one standard php-server, and the nodejs-server works with the neat iisnode package.

我在windows 10上有两个运行在iis上的本地主机安装,一个标准的php-server, nodejs-server与整洁的iisnode包一起工作。

The 'real' server is run on ubuntu.

真正的服务器是在ubuntu上运行的。

I think this is a neat and easy solution for communication between two servers, but maybe someone has any comments about it?

我认为对于两个服务器之间的通信来说,这是一个简洁而容易的解决方案,但是也许有人对此有什么看法?