Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js running alongside Apache PHP?

I am trying to get my head round node.js...

I am very happy with my LAMP set up as it currently fulfils my requirements. Although I want to add some real-time features into my PHP app. Such as showing all users currently logged into my site and possible chat features.

I don't want to replace my PHP backend, but I do want scalable real-time solutions.

1. Can I throw node.js into the mix to serve my needs without rebuilding the whole application server-side script?

2. How best could node.js serve my 'chat' and 'currently logged in' features?

Great to hear your views!

W.

like image 656
wilsonpage Avatar asked Jan 09 '11 20:01

wilsonpage


People also ask

CAN node js and PHP work together?

Yes, and yes. Node and Apache / PHP can co-exist on a single server.

Can you run Apache and node at the same time?

Since we cannot run both node. js server and the Apache server to listen on same port, we need to config Apache to act like a reverse proxy and pass the request to node. js application for a specific URL. For example, if you have the Apache server running on localhost and want to run node.

Is nodejs same as Apache?

A node. js web application is a full-fledged web server just like Nginx or Apache. Indeed, some projects use node. js as the front-end load balancer for other servers (including Apache).


1 Answers

I suggest you use Socket.io along side node.js. Install and download the libs from http://socket.io/. You can run it along side your Apache server no problems.

First create a node server:

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 

Second, run your server from the command line using:

node /path/to/your/server.js 

Third, connect to the socket using client side js:

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

You will have to have include the socket.io lib client side aswell.

Send data from client side to the node server using:

socket.send({data:data}); 

Your server.js should also have functions for processing requests:

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

There are two main ways to send data from the server to the client:

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 
like image 146
Kit Avatar answered Sep 18 '22 21:09

Kit