Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include Node.JS + Socket.IO in Symfony2 application

I have done many researches and it seems I can't find the proper solution. I am confident in PHP. I also have done some tutorials on Node.JS and Socket.IO and I'm currently learning Symfony2 but I can't see how I can merge the two to achieve my goal.

My goal is to set up real-time notification for back-end users of my app. This app is a e-commerce website and I want the admin behind the scenes to be warned as soon as an order is made by a visual notification in the upper right corner of the admin panel. My server use FreeBSD.

My plan is to use Node.JS and Socket.IO to achieve this. If there is a better plan, I'm willing to hear about it. Otherwise, I cannot find proper resources to tell me how I can include Node.JS and Socket.IO to a Symfony2 app. I use composer to install bundles but I haven't used NPM with Symfony2.

I have found this question, this link and this other question to help me out but none of these tell me how I can install Node.JS in a Symfony2 app.

If someone could help me with the steps to complete to make me start developping this feature, I'd be glad.

Thanks!

like image 401
D4V1D Avatar asked Dec 24 '22 21:12

D4V1D


1 Answers

For those who might be interested in the answer:

$ su -

Install Node.JS

$ cd /usr/ports/www/node

$ make install clean

Install NPM

$ cd /usr/ports/www/npm

$ make install clean

Install Socket.IO

$ cd /path/to/your/project/js/public/files

$ npm install socket.io

Develop the code

app.js

var http = require('http');
var fs = require('fs');

var server = http.createServer(function(req, res) {
    fs.readFile('./index.html', 'utf-8', function(error, content) {
        res.writeHead(200, {"Content-Type": "text/html"});
        res.end(content);
    });
});

var io = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {
    socket.on('newOrder', function () {
        socket.broadcast.emit('message', 'Nouvelle commande');
    });
});

server.listen(4321);

Front-end

<script src="{{ asset('http://localhost:4321/socket.io/socket.io.js') }}"></script>

<script>
    jQuery(function($) {
        var socket = io.connect('http://localhost:4321');

        $('form').on('submit', function() {
            socket.emit('newOrder', '1');
        });

    });
</script>

Back-End

<script>
    jQuery(function($) {    
        var socket = io.connect('http://localhost:4321');

        socket.on('message', function(message) {
            alert(message);
        });
    });

</script>

Launch server

$ node app.js

That's all!

like image 73
D4V1D Avatar answered Dec 27 '22 20:12

D4V1D