Eliasdx
Eliasdx

Reputation: 2180

Socket.IO: Invoke custom function instead of using socket.on

Is there a way I can define a custom function (name,data,callback) which is then invoked by socket.io when a client sends a function call?

Instead of using socket.on(name,function(data,callback){...}) socket.io should call my function. This would make it much easier to implement logic that is needed in every socket.io function and I wouldn't need to call socket.on for a whole stack of rpc functions on each connection.

I checked socket.io wiki but didn't find anything related.

I know I could implement a "rpc server" on top of socket.io like this, but it would be better to use socket.io's native way.

socket.on('rpc',function(data,callback){ /* e.g. data.name for function name, data.data for the actual data */});

Upvotes: 1

Views: 1988

Answers (1)

Juliusz Gonera
Juliusz Gonera

Reputation: 4958

Not sure if I get it. Can't you do something like this?

Server:

function handleMessage(name, data, callback) {
  // ...
}

// listen on all kind of messages
socket.on('message', handleMessage);

Client:

socket.send(name, data, callback);

This way you just use Socket.IO as a WebSockets wrapper.

If you are looking for something more fancy maybe you should check out nowjs or dnode.

Upvotes: 3

Related Questions