php 如何集成nodeJS + Socket.IO 和PHP?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17209717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to integrate nodeJS + Socket.IO and PHP?
提问by Jérémy Dutheil
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).
我最近一直在环顾四周,以找到一种在 nodeJS 和 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 和 Node 服务器之间进行通信。我想要的是能够在简单的 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 ! ;)
希望这可以帮助一些人!;)
回答by Jérémy Dutheil
So, to begin with, I put my project on github, if you want access to the full code: https://github.com/jdutheil/nodePHP
所以,首先,我把我的项目放在 github 上,如果你想访问完整的代码:https: //github.com/jdutheil/nodePHP
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.
这是一个非常简单的示例项目:网络聊天。你只有一个作者和消息,当你按下发送时,它被保存在一个 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 which script include to be able to run Socket.IO code without the nodeServer (because client page will be served by Apache).
当新用户连接时,我们注册了我们的事件回调;每次我们收到一条消息(代表一条聊天消息)时,我们都会将其广播给每个连接的用户。现在,棘手的部分:客户端!这部分花费了我大部分时间,因为我不知道包含哪个脚本才能在没有 nodeServer 的情况下运行 Socket.IO 代码(因为客户端页面将由 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:
但一切都已经完成了;当您使用 npm 安装 Socket.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. ;)
最后,我的 nodeClient.js,我们只需连接到节点服务器并等待事件更新我们的页面。;)
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!
希望这可以帮助一些人!
回答by Snorvarg
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 iisnodepackage.
我有两个 localhost-installations 在 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?
我认为这是用于两台服务器之间通信的简洁而简单的解决方案,但也许有人对此有任何评论?
回答by vikujangid
Try similar or you can check my blog for complete sample code on nodejs
尝试类似,或者您可以查看我的博客以获取有关 nodejs 的完整示例代码
On your page side:
在您的页面方面:
- Load Socket JS
- 加载套接字 JS
https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js
https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js
- Make object of the socket
- 制作套接字的对象
var socket = io();
var socket = io();
- Use the
emitfunction to send data to nodeserver.
- 使用该
emit函数向节点服务器发送数据。
socket.emit('new_notification', {
message: 'message',
title: 'title',
icon: 'icon',
});
socket.emit('new_notification', {
message: 'message',
title: 'title',
icon: 'icon',
});
So now your code will be look like
所以现在你的代码看起来像
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
var socket = io();
$(document).ready(function($) {
$('.rules-table').on('click', '.runRule', function(event) {
event.preventDefault();
/* Act on the event */
var ruleID = $(this).parents('tr').attr('id');
// send notification before going to post
socket.emit('new_notification', {
message: 'Messge is ready to sent',
title: title,
icon: icon,
});
$.ajax({
url: '/ajax/run-rule.php',
type: 'POST',
dataType: 'json',
data: {
ruleID: ruleID
},
})
.done(function(data) {
console.log(data);
// send notification when post success
socket.emit('new_notification', {
message: 'Messge was sent',
title: title,
icon: icon,
});
})
.fail(function() {
console.log("error");
// send notification when post failed
socket.emit('new_notification', {
message: 'Messge was failed',
title: title,
icon: icon,
});
})
.always(function() {
console.log("complete");
});
});
});
Now on Node server side make handler for your request to get your request and send a message to all connected devices/browsers(server.js)
现在在节点服务器端为您的请求制作处理程序以获取您的请求并向所有连接的设备/浏览器发送消息(server.js)
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res) {
res.sendfile('index.html');
});
io.on('connection', function (socket) {
socket.on( 'new_notification', function( data ) {
console.log(data.title,data.message);
// Now Emit this message to all connected devices
io.sockets.emit( 'show_notification', {
title: data.title,
message: data.message,
icon: data.icon,
});
});
});
http.listen(3000, function() {
console.log('listening on localhost:3000');
});
Now the client/browser/client side make a receiver to receive socket message from node server
现在客户端/浏览器/客户端创建一个接收器来接收来自节点服务器的套接字消息
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
var socket = io();
/**
* Set Default Socket For Show Notification
* @param {type} data
* @returns {undefined}
*/
socket.on('show_notification', function (data) {
showDesktopNotification(data.title, data.message, data.icon);
});
/**
* Set Notification Request
* @type type
*/
function setNotification() {
showDesktopNotification('Lokesh', 'Desktop Notification..!', '/index.jpeg');
sendNodeNotification('Lokesh', 'Browser Notification..!', '/index.jpeg');
}
/**
* Check Browser Notification Permission
* @type window.Notification|Window.Notification|window.webkitNotification|Window.webkitNotification|Window.mozNotification|window.mozNotification
*/
var Notification = window.Notification || window.mozNotification || window.webkitNotification;
Notification.requestPermission(function (permission) {
});
/**
* Request Browser Notification Permission
* @type Arguments
*/
function requestNotificationPermissions() {
if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
});
}
}
/**
* Show Desktop Notification If Notification Allow
* @param {type} title
* @param {type} message
* @param {type} icon
* @returns {undefined}
*/
function showDesktopNotification(message, body, icon, sound, timeout) {
if (!timeout) {
timeout = 4000;
}
requestNotificationPermissions();
var instance = new Notification(
message, {
body: body,
icon: icon,
sound: sound
}
);
instance.onclick = function () {
// Something to do
};
instance.onerror = function () {
// Something to do
};
instance.onshow = function () {
// Something to do
};
instance.onclose = function () {
// Something to do
};
if (sound)
{
instance.sound;
}
setTimeout(instance.close.bind(instance), timeout);
return false;
}

