Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to integrate nodeJS + Socket.IO and PHP?

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).

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.

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

like image 201
Jérémy Dutheil Avatar asked Jun 20 '13 09:06

Jérémy Dutheil


People also ask

Can I use Socket.IO with PHP?

the phpwebsocket class is indeed the way to go if you want a php websocket server implementation. However this is not related to the question. The OP already has a WS server (socket.io) implemented and asked for ways to communicate with a php application.

Can we use Nodejs and PHP together?

You can run node and PHP on same server, and even on the same port. The key is to use a server like nginx in front listening on port 80, set up PHP in Nginx as you normally would (using php-fpm) and set up your Node instance to listen locally on some high port like 8081.

Can I use Socket.IO without node JS?

Is it possible to use socket.io without any node. js dependencies? The short answer is yes. You will however have Flash dependency.


2 Answers

So, to begin with, I put my project on github, if you want access to the full code: 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.

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.

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

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).

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:

    <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!

like image 161
Jérémy Dutheil Avatar answered Sep 23 '22 19:09

Jérémy Dutheil


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:

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():

$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.

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.

The 'real' server is run on ubuntu.

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

like image 26
Snorvarg Avatar answered Sep 25 '22 19:09

Snorvarg