mardi 31 mars 2015

Dynamic attach event to socket (socket.io)

In this example code "offer" event transmits some data from one client to another through server. Although, it doesn't works now)



//server side
var ioSpace = io.of('/channel_name');
ioSpace.on('connection', function(socket) {
var calleeID = '1e-hBUBhwhUUQo8pAAAC';

socket.on('offer', function(data) {
var callee = io.sockets.connected[calleeID];
callee.nsp.name = '/channel_name';

callee.once('answer', function(data) {
//To do something
});

callee.emit('offer', data);
});
});


This data transmitted to server from second client.



42/channel_name,["answer",<some data>"type":"answer"}]


but event 'answer' don't working.


And this code



callee.nsp.name = '/channel_name';


looks dirty. Anybody know how best to do here?


It task can be solved with another flags/if/else logic, but interesting concrete this approach - get socket with its namespace by id, attach once event to it, send data and waiting answer.


socket.io 1.3.5, node.js 0.12.0.




So. After some code and manual reading:



//server side
var ioSpace = io.of('/channel_name');
ioSpace.on('connection', function(socket) {
var calleeID = '1e-hBUBhwhUUQo8pAAAC';

socket.on('offer', function(data) {
var callee = ioSpace.connected[calleeID];

callee.once('answer', function(data) {
//To do something
});

callee.emit('offer', data);
});
});

Aucun commentaire:

Enregistrer un commentaire