Note that there are some explanatory texts on larger screens.

plurals
  1. POSimple chat with socket.io
    primarykey
    data
    text
    <p>I'm trying to implement a very simple chat with socket.io, and i'm getting into a really weird problem.</p> <p>server side:</p> <pre><code>var users = {}; io.sockets.on('connection', function (socket) { socket.on('join', function(userNameParam) { socket.join('chatchannel'); users[userNameParam] = userNameParam; socket.userName = userNameParam; socket.emit('firstLogin',users); socket.broadcast.to('chatchannel').emit('addConnectedUser',userNameParam); }); }); </code></pre> <p>client side:</p> <pre><code>var socket = io.connect(); function onLogInLogOutClick() { var userName = document.getElementById("txtUserName").value; // get button text var btnLogInLogOut = document.getElementById('btnLogInLogOut'); var txtBtnLogInLogOut = btnLogInLogOut.textContent || btnLogInLogOut.innerText; if(txtBtnLogInLogOut == 'LogIn') { // send join message socket.emit('join', userName); } } </code></pre> <p>When I login in the first browser tab (for the first user) everything works great, but when I login in the second browser tab (for the second user), for some unknown reason 'join' event on the server side gets called more than once!</p> <p>I've read on the API that 'socket.emit' suppose to raise the event only for the current request socket client, so what can be the issue ?</p> <p><strong>UPDATE:</strong></p> <p>I looked at the socket.id on the first and second call, and it's the same. why does it happen?</p> <p><strong>UPDATE 2:</strong></p> <p>On the second tab, when reaching to the server side, I see that the request socket is subscribing TWICE to each event. I don't know why.</p> <p><strong>UPDATE 3:</strong></p> <p>Found the problem: server code was placed here:</p> <pre><code>module.exports = function(app, socketio, loggerInstance) { io = socketio; app.get('/chat',chat); }; var chat = function(req, res){ *** SERVER CODE THAT WAS WRITTEN ABOVE *** res.render('chat'); }; </code></pre> <p>I moved the server code to 'app.js' file and it works fine.</p> <p>Still I can't figure out why those events were called more than once.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload