vendredi 27 octobre 2017

Using socket.io with a server created with serve-static in Node.js

I'm trying to use data on server-side Node.js and use it dynamically in my web-page. In order to start my page, I do the following:

var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic("../../")).listen(5500, function(){
    console.log('server is now running on 5500...');
});

What I want to do is to involve socket.io concept with this code and make certain pages communicate with variables in node.js server side.

Using what's already done in Using data between javascript and Node.js? for me would be a good starting point. However. I would love to use serve-static instead of starting a http server, because it is able to serve my whole web-page flawlessly. And I'm wondering if I can use the approach described in the link for serve-static. For example, I'm wondering something like following would work (listening serveStatic):

var connect = require('connect');
var serveStatic = require('serve-static');
var myserver = connect().use(serveStatic("../../")).listen(5500, function(){
    console.log('server is now running on 5500...');
});

var io = require('socket.io').listen(myserver);
io.sockets.on('connection', function(socket) {

    // Receive data
    socket.on('my-data', function(data){

         // Do something with your data

         // Send modified data
         socket.emit('my-modified-data', modified_data);
    });
});

If I am missing some info, please let me know as I'm pretty new to the Node.JS. Any guidance is well appreciated and thank you in advance.




Aucun commentaire:

Enregistrer un commentaire