Closed muriloinflue closed 6 years ago
Yes u are right, third param is not callback (third param is special internal param for application to work properly). Unfortunately ClusterWS does not have callback yet, i will look in to adding it to the application.
if u are looking in case of error on sending message i think it is better use method on error.
@goriunov Thanks for the reply. You'll probably have a much better implementation of it, but this is how I did it:
On the client:
var socket = new ClusterWS(options);
var packet_id = 0;
var callbacks = [];
socket.on('callback',function(feed) {
var fn = callbacks[feed.id];
if (fn) fn(feed.data);
});
socket.callback = function(feed,data,callback) {
this.emit('callback',{'id':feed.packet_id,'data':data},callback);
};
socket.emit = function(channel,data,callback) {
data.packet_id = packet_id;
callbacks[packet_id] = callback;
packet_id++;
socket.send(channel,data);
};
On the server:
wss.on('connection',function(socket) {
var packet_id = 0;
var callbacks = [];
socket.on('callback',function(feed) {
var fn = callbacks[feed.id];
if (fn) fn(feed.data);
});
socket.callback = function(feed,data,callback) {
this.emit('callback',{'id':feed.packet_id,'data':data},callback);
};
socket.emit = function(channel,data,callback) {
data.packet_id = packet_id;
callbacks[packet_id] = callback;
packet_id++;
socket.send(channel,data);
};
});
That way I can use the socketio-style of sending and receiving data :) Example:
Server-side
socket.on('client',function(feed) {
if (feed.event == 'ready2rock') {
socket.callback(feed,{event:'alert',msg:'Rock it!'},function() {
console.log('Client is rocking!');
});
}
});
Client-side
socket.emit('client',{event:'ready2rock'},function(feed) {
if (feed.event == 'alert') {
alert(feed.msg);
socket.callback(feed,{status:true});
}
});
That is cool, i am going to check it out and possibly add to new 3.0 release, hopefully it should be up and running in a week or so.
Submitting
Details
What version of ClusterWS do you use (you can find it in package.json) 2.2.1
The operating system you are running on. Windows 8.1 64bit
Describe the problem as clear as possible. It's simple, actually. I came to clusterWS from socket.io, so, the question is: How to use callbacks on socket.emit ? Whenever I put a third parameter on it (1st: channel, 2nd: data, 3rd... callback?), the server gives an "SyntaxError: Unexpected token u in JSON at position 0" error, which based on other issues, makes me think it's because the 3rd parameter is not supposed to be a callback/function-type.