Dan
Dan

Reputation: 57881

Socket IO publish-subscribe model tricky

The problem is on socket.io client side.

I want first to create unconnected socket, and connect it to server after assigning all the listeners. The listeners cannot be set synchronously in one place in my application because there are some dependencies.

I know it's quite normal behavior normal for node.js! Just look at nodejs's sockets! I hope there's nothing wrong with my architecture. Socket io lacks documentation and I can't find how to do what I want:

var socket = new io.Socket(); //creating empty socket.But this line does not work

//..... socket variable can be passed somewhere .....
//..... to another place in app .....

socket.on('message', callback);

//..... when everyone is ready and subscriben .....

socket.connect('some-url');

Upvotes: 0

Views: 1168

Answers (3)

Dan
Dan

Reputation: 57881

I've found what I was looking for in the socket.io documentatuion

They write we can disable connecting to the server in the moment of socket construction by setting this config:

auto connect defaults to true

When you call io.connect() should Socket.IO automatically establish a connection with the server.

So now we construct the object and it does not create connection immediately.

After constructing the unconnected socket you call method create()

I still don't know how to turn off the connection. So watch for updates

Upvotes: 1

Florian Margaine
Florian Margaine

Reputation: 60717

So you want to start socket.connect() when something happens? So a classical click event listener like this:

$('#button').click(function() {
    socket.connect('some-url')
});

If you want to listen to messages only after an event occurs, do the following:

socket.connect('some-url')
document.getElementById('button').onclick = function() {
    socket.on('message', function() {
        // Your stuff
    }
} 

Upvotes: 1

lennel
lennel

Reputation: 646

If I understand your issue correctly, if you create a socket without connecting immediately, all event listeners you added to it get disregarded once you connect it. That would be crap, I have not played with socket yet, so I cannot validate if it is true or not, but I have a solution for the problem

Create a facade which you add all your listeners too, once you are abale to connect to the server, connect, add your listeners (this should be done synchronously) and proxy all events dispatched by the socket through your facade.

Upvotes: 1

Related Questions