peerxu
peerxu

Reputation: 652

any way to send a function with socket.io?

guys.

I want to send a function to browser with socket.io, but failed to do it.

On server side, I response a function with emit, but I get a undefined on browser.

Is there any way to get a function from server with socketio?

there is my code.

// server.js
var static = require('node-static');
var http = require('http');
var file = new(static.Server)();
var app = http.createServer(function(req, res) {
    file.serve(req, res);
}).listen(8000);

io = require('socket.io').listen(app);
io.sockets.on('connection', function(socket) {
    socket.on('schedule', function() {
        console.log('SCHEDULE TASK');
        socket.emit('schedule', function() { console.log('hello world'); });
    });
});

// client.js

var socket = io.connect('http://localhost:8000');
socket.on('schedule', function(fn) {
    fn();
});
socket.emit('schedule');

Upvotes: 1

Views: 1247

Answers (2)

jfriend00
jfriend00

Reputation: 707856

You cannot send an actual function. You could send a string of Javascript and then you could turn that into a function in the client.

But, I'd suggest you really ought to rethink what you're trying to do here. Generally, the client already has the code it needs (from the script tags that it downloaded) and you send the client data which it then passes to the code it already has or data that it uses to make decisions about which code that it already has to call.

If you show us the real world problem you're trying to solve, we can likely suggest a much better solution than sending a string of Javascript code to the client.

If you really wanted to send a function, you would have to turn it into a string first, send the string, then use the string to turn it back into a function in the client by using a Function object or eval() or creating your own dynamic script tag with inline source.

Upvotes: 3

Lewis
Lewis

Reputation: 14906

You can only send strings via socket.io, not functions. That being said, I suggest you to send function names instead.

//server.js
socket.emit('schedule', 'helloworld');

//client.js
function helloworld(){
    console.log('hello world');
}
socket.on('schedule',function(name){
    window[name](); //hello world
});

Upvotes: 1

Related Questions