node.js 与 Apache PHP 一起运行?

2024-04-21

我正在尝试了解 Node.js...

我对我的 LAMP 设置非常满意,因为它目前满足我的要求。虽然我想在我的 PHP 应用程序中添加一些实时功能。例如显示当前登录我的网站的所有用户以及可能的聊天功能。

我不想更换我的 PHP 后端,但我确实想要可扩展的实时解决方案。

1. 我可以将 node.js 加入其中来满足我的需求,而无需重建整个应用程序服务器端脚本吗?

2. Node.js 如何最好地为我的“聊天”和“当前登录”功能提供服务?

很高兴听到您的意见!

W.


我建议您将 Socket.io 与 node.js 一起使用。安装并下载库http://socket.io/ http://socket.io/。您可以在 Apache 服务器旁边运行它,没有任何问题。

首先创建一个节点服务器:

var http = require('http')
  , url = require('url')
  , fs = require('fs')
  , io = require('../')//path to your socket.io lib
  , sys = require(process.binding('natives').util ? 'util' : 'sys')
  , server;

server = http.createServer(function(req, res){
  var path = url.parse(req.url).pathname;
}),

server.listen(8084);//This could be almost any port number

其次,使用以下命令从命令行运行服务器:

node /path/to/your/server.js

第三,使用客户端js连接到套接字:

var socket = new io.Socket(null, {port: 8084, rememberTransport: false});
socket.connect();

您还必须包含 socket.io lib 客户端。

使用以下命令将数据从客户端发送到节点服务器:

socket.send({data:data});

您的 server.js 还应该具有处理请求的函数:

io.on('connection', function(client){
//action when client connets

 client.on('message', function(message){
    //action when client sends msg
  });

  client.on('disconnect', function(){
    //action when client disconnects
  });
});

从服务器向客户端发送数据主要有两种方式:

client.send({ data: data});//sends it back to the client making the request

and

client.broadcast({  data: data});//sends it too every client connected to the server
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

node.js 与 Apache PHP 一起运行? 的相关文章

随机推荐