Pregunta

I'm programming on the NodeJS server side, I wish to call a javascript function on the client browser side. Hopefully I can call functions every now and then on the client browser side from the server side as if I an just calling the function on the server side.

Is there some form or comet or RPC which can do this?

¿Fue útil?

Solución

I checked out Socket.IO but ended up using Faye instead. Faye is probably a little more functionality than you want, but it's so easy to setup and use. I found it more intuitive than Socket.IO. Not that Socket.IO looks tough, but Faye just looked easier.

Here is the website:

http://faye.jcoglan.com/

There is a google users group too and the author has responded to a couple of my inquiries.

What you would need is the following code:

Node side:

var faye = require('faye');
var faye_server = new faye.NodeAdapter({mount: '/faye', timeout: 120});

console.log('Firing up faye server. . . ');
faye_server.listen(8089);

//send message out every 1 second
setInterval( function()
{   
    var currentTime_secsSinceEpoch = new Date().getTime() / 1000;

    faye_server.getClient().publish('/heartbeat', 
    {
        pageName: 'app.js',
        timeMessageSent_secs_since_epoch: currentTime_secsSinceEpoch,
        iFrame1CycleCount: iFrame1CycleCount

    });
}, 1000);

Browser Side:

<script type='text/javascript'>
//create faye client
var faye_client = new Faye.Client('http://127.0.0.1:8089/faye');

var faye_message_subscription = faye_client.subscribe('/heartbeat', function(message)
{   
    //record the time message was received
    var receiveTime_secSinceEpoch = new Date().getTime() / 1000;

    console.log("Got heartbeat at " + receiveTime_secsSinceEpoch + "with a delay of " +
        receiveTime_secsSinceEpoch - message.currentTime_secsSinceEpoch + " secs");
    //Do something else important here!!
}
</script>

That's it! Now every time your server sends the 'heartbeat' message, your webpage will call the function we specified and spit out a message to the console. Dead simple.

Faye has a lot of other cool functionality you may want to use, but this is mostly what you will want I think.

You can attach Faye to an express server in node too really easily which makes it work really well with a webserver.

Otros consejos

Using socket.io emit an event from server ("for_client" in this case) which the client listens to and set a listener for client side events ("for_server" in this case). There can be any number of events and they can have a callback which can be used to invoke methods.

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

io.sockets.on('connection', function (socket) {
  socket.emit('for_client', { someData: 'if necessary' });
  socket.on('for_server', function(data) {
     doSomethingServerSide(data);
  });
});

function doSomethingServerSide(data){ console.log(data); }

On Client side

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('for_client', function (data) {
    console.log(data);
    socket.emit('for_server', { data: 'data' });
  });
</script>

Socket.IO will allow you to establish persistent communication between node.js and front-end JS.

You can emit messages and subscribe to any other messages from both sides. As it is bidirectional communication, you dont need any request/response stuff, just emit from any side, and it will be cached by callback on another side.

You will have to use Socket.IO to form web-socket connection which allows sending data from any side to the other after one initial connection has been made. Socket.IO has many fall back methods that it uses if web-socket is not allowed in the user's browser.

So you can add an event-binder in your client-side code which will respond to any data sent from the nodejs server side and thus you can execute client-side function from the server itself.

But if your looking for something that you define a function in client-side and you can directly call it from nodejs, than you are mistaken. Though they are both javascript but they are entirely different in terms of execution. NodeJs is javascript on server-side and not for both at once. But still as I said above you can execute a client-side function using Socket.IO and event binders.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top