Let's suppose I have a website that DOESN'T require web-sockets on the home page, but DOES require it on some other relative path ('/new' for example).
Suppose I need the 'connection' event in order to count users that login to the 'home' page and to the 'new' page.
I've tried to configure socket.io 'connection' event in the relative path like:
app.get('/new',
function(req,res) {
io.sockets.on('connection', function (socket) {
.....
}
});
BUT:
How can it be done ?
Answering your questions:
Obviously, because when a user hits /new
its handler fires and adds connection handler to io
. It's a huge memory leak.
That's related to the one above. You don't want to add a connection handler every time a user hits /new
.
Now to solve your problem I think that the best idea is to call (on the browser side)
io.connect("http://localhost/new");
and then in your Node.js app:
io.of("/new").on("connection", function (socket) {
// here are connections from /new
});
The code should be placed at the top level, not inside a route handler. If you want it to be more dynamic, then you can create your own sub-protocol:
io.connect("http://localhost)
;I'm in /new
;Of course you can specify in your route handler whether you want your client to connect to socket.io server or not (simply by passing some kind of flag).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With