node.js - socket io doesn't work both way? -
my current problem there 2 browsers (two users). once both of them connected, socket event friends request not both @ same time. need refresh 1 of user's page.
illustratively
when user click button
the navbar glyphicon incremented 1
serverside event
io.on('connection', function(socket){ // everytime user connected, database operation store socketid, user.socketid = socket.id; // simplicity. console.log(socket.request.user.username); // using passport-socket.io library socket.on('friendsrequest', function(data) { // got these 2 datas input hidden on html using jquery var socketid = data.socketid; var userid = data.userid; socket.to(socketid).emit('friendsrequest', socket.request.user); console.log("successful" + " " + socket.request.user.username); });
the weird thing , on serverside showing console.log("successful" + " " + socket.request.user.username);
meaning if click button on both user's browser show correctly
"successful usera" "successful userb"
but problem on clientside, targeted html never changed, 1 of browser navbar's glyphicon incremented
here's code on client side
// event send targeted data socketid , userid server $(document).on('click', "#addfriend", function(e){ e.preventdefault(); var userid = $('#userid').val(); var socketid = $('#socketid').val(); socket.emit('friendsrequest', { userid: userid, socketid: socketid }); }); // once server has done doing job, event listen. socket.on('friendsrequest', function(data) { var totalrequests = parseint($('#totalrequests').html()); console.log(totalrequests); totalrequests += 1; $('#totalrequests').html(totalrequests); $('#friendsrequested').append('<li>' + data + '</li>'); });
the main problem on clientside socket.on('friendsrequest');
it works of 1 of browsers not both @ same time when fired friendsrequest event
need socket.io expertise explain me why doesn't work both ways. logic supposed work.
html
<input type="hidden" name="socketid" id="socketid" value="valueofthesocketid" /> <button type="submit" id="addfriend" class="btn btn-default">add friend</button>
if event 'friendsrequest' not fired error when emit on server:
socket.to(socketid).emit('friendsrequest', socket.request.user);
it socketid not correct, why? :
the socket.id reset when reconnection occurs. cause when do: socket.to(socketid).emit('friendsrequest', socket.request.user); sent anyone.
a reconnection can happen when error occurs inside event listener on client (it not appear on console).
so watch if happens can use default event 'disconnect' on server:
socket.on('disconnect', function () { console.log('user disconnected'); });
Comments
Post a Comment