Saturday, 13 May 2017

Socket.io listen to two different connections on a single page app without page reload

so i have a MEAN app, and I am trying to listen to connections on two different namespaces. The problem is that since it is a spa, the connection works only when I reload the two pages.

    function socketFunction(io, url, event){
    const blog = io.of(`/articles/${url}`)
    const admin = io.of('/admin/home')
    blog.on('connection', (fromBlog)=>{
        console.log("Connection made on blog");
        fromBlog.on('comment', (msg)=>{
            event.emit('comment-posted', msg)
        })
    })
    admin.on('connection', (toAdmin)=>{
        console.log("Connection made on admin");        
        event.on('comment-posted', (msg)=>{
            toAdmin.emit('blog-comment', msg)
        })
    })
}

export {socketFunction}

My node server starts on / and the two angularjs clients do their job handle the rest of the routes.

I want the connection to open, only when the host is localhost:port/articles/:url, and i am not able to make socket.io aware of this without reloading the page.

here is the server code that fires the socketFunction function.

 const blogRoutes = ['/', '/articles', '/articles/:url', '/contact'];

blogRoutes.forEach(el=>{
  app.get(el, (req, res)=>{
    if(el === '/articles/:url'){
      socketFunction(socket, req.params.url, myEvent)
    }
    res.sendFile(path.join(__dirname, '/client', '/blog', '/blog.html')); 
  })
})

const server = app.listen(process.env.PORT, process.env.IP, ()=>{
      console.log(`Express server listening on port ${process.env.PORT} and IP ${process.env.IP}`);
    });

    var socket = io(server)



via Ayush Bahuguna

No comments:

Post a Comment