node.js和Apache PHP一起运行?

wil*_*age 31 php apache server-side serverside-javascript node.js

我试图让我的头围绕node.js ...

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

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

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

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

很高兴听到你的意见!

W.

Kit*_*Kit 23

我建议你在side node.js上使用Socket.io.从http://socket.io/安装并下载libs .您可以在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
Run Code Online (Sandbox Code Playgroud)

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

node /path/to/your/server.js
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

socket.send({data:data});
Run Code Online (Sandbox Code Playgroud)

您的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
  });
});
Run Code Online (Sandbox Code Playgroud)

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

client.send({ data: data});//sends it back to the client making the request
Run Code Online (Sandbox Code Playgroud)

client.broadcast({  data: data});//sends it too every client connected to the server
Run Code Online (Sandbox Code Playgroud)

  • 嗨@Kit感谢您的回答.关于连接Apache部分,我仍然有点困惑.您是否介意在答案中添加一些注释/代码以使Apache部分更清晰? (3认同)