0

I have a problem with code I copied directly from socket.io website. I have the server setup and it's running fine. The problem is it's duplicating each event after the first event fired:

enter image description here

I read here: Socket.io message event firing multiple times

That it's because of the events re-registering each time. But nowhere does it actually say how to stop this and fix this.

Since my code is a direct copy off of Socket's site, I'm really baffled as multiple Google searches only come up with vague information and never really a true way to fix it.

This is my basic code:

var util = require('util'),
    express = require('express'),
    http = require('http').Server(express),
    https = require('https').Server(express),
    io = require('socket.io')(http),
    config = require('./config'),
    phash = require('phpass').PasswordHash,
    bodyParser = require('body-parser'),
    mysql = require('mysql'),
    ip = require('ip');

var connection = mysql.createConnection({
    host: config.dbhost,
    user: config.dbuser,
    password: config.dbpass,
    database: config.dbname
});

var app = express();

connection.connect(function ( err ) {
    if(!err) {
        console.log("Database is connected ... \n\n");  
    } else {
        console.log("Error connecting database ... \n\n");  
    }
});

http.listen(config.port);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

io.on('connection', function ( socket ) {
    socket.on('newboard', function ( data ) {
        console.log(data);
        connection.query('MYSQL', function ( err, rows, fields ) {
            if (!err) {
                console.log('The solution is: ', rows);
                io.sockets.emit('messageSuccess', { bid: rows.insertId });
            } else
                console.log('Error while performing Query. '+err);
        });
    });

    socket.on('changeboard', function ( data ) {
        console.log(data);
        connection.query('MYSQL', function ( err, rows, fields ) {
            if (!err) {
                console.log('The solution is: ', rows);
                io.sockets.emit('messageSuccess', rows);
            } else
                console.log('Error while performing Query. '+err);
        });
    });
});

UPDATE

As per request, my client side code:

var socket = io.connect('http://localhost:8080');

socket.emit('newboard', { title: boardTitle, usid: 1 });
socket.on('messageSuccess', function ( data ) {
    bid = data.bid;
});

socket.emit('changeboard', { bid: id });
socket.on('messageSuccess', function ( data ) {
    console.log(data);
    for (i = 0; i < data.length; i++) {
        //Code run on local HTML
    }
});

As stated, it only does it after the second call to newboard and changeboard. Then it starts doubling up. If I keep going it just keeps doubling up until I have 30 some boards and refresh the page.

UPDATE2

Full code for client area can be found here: http://pastebin.com/dkgy4VUx

Community
  • 1
  • 1
jfreak53
  • 2,239
  • 7
  • 37
  • 53
  • 2
    I don't see any obvious cause of duplicates in your server code. Next best guess is the client code making more than one connection. Can we see the client code? I do see that each time your server recieves a message from a **single** client, it sends out a message to **all** the clients. I'm guessing that that is not your intent. You could fix that in your server code by using `socket.emit(...)` instead of `io.sockets.emit(...)` to send only to the one socket. – jfriend00 Jun 12 '15 at 23:41
  • Sorry for the delay. I've added the client side code above to the original post. – jfreak53 Jun 15 '15 at 13:46
  • show the output of the server too if you can. This said, this code is neat. So i wonder how look like the subscribe / trigger event on client side. Also i wonder if you are not misunderstanding io.sockets.emit / socket.emit on server side as said by jfriend00. –  Jun 15 '15 at 13:55

1 Answers1

1

I'm guessing that this code is in some kind of function that you call more than once:

socket.emit('changeboard', { bid: id });
socket.on('messageSuccess', function ( data ) {
    console.log(data);
    for (i = 0; i < data.length; i++) {
        //Code run on local HTML
    }
});   

So, each time you call that function, you are installing another duplicate event handler for the messageSuccess message. So, after you've called the function twice, you have two event handlers for that message and you will process it twice.

You cannot repeatedly add message handlers unless you also remove them (because you get duplicate handlers). Message handlers should generally be added once when the socket connection is first created.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Aha! Ok, so at the document ready stage. Great, but if I do that how do I make the call when things happen? – jfreak53 Jun 15 '15 at 17:41
  • 1
    @jfreak53 - not a document ready time. Right after you create the socket is when you generally add the event handlers. The way socket.io is designed, you should be using a unique message for a unique event handler. Thus, you should be able to install the event handler for a given message once. So, don't use `messageSuccess` for two different things. Use a different message name for each. – jfriend00 Jun 15 '15 at 17:44
  • My not understanding is still, ok, I've registered `changeboard` under my main script tag. Great. Now when X user on the page clicks the Add Board `a` link, how do I tell the registered `newboard` function to send the new title and id? That's what I'm not understanding. – jfreak53 Jun 15 '15 at 17:48
  • 1
    @jfreak53 - Change your server so it doesn't use the same `messageSuccess` message to mean different things. Make a `changeboardSuccess` and a `newboardSuccess`. Then, you can install the event handlers for each of those messages once and not get duplicates. – jfriend00 Jun 15 '15 at 17:50
  • It's still doubling up after the first `newboard` is sent. I've created new messages for each event now. But still doubling up it seems. – jfreak53 Jun 15 '15 at 21:07
  • @jfreak53 - I can't help you any further without seeing the real client code. Not cut out pieces of code, not code changes you try to describe in words, but the whole context of the relevant code. You can use the "edit" link to add it to the end of your question. – jfriend00 Jun 15 '15 at 21:14
  • 1
    @jfreak53 - like I've said several times now, you are calling `socket.on('updateboardSuccess', ...)` multiple times. Every time you call that it installs another event handler which will process the message multiple times. For example, every time you call `addCard()`, you install yet another `socket.on('newcardSuccess', function ( data ) {...})` event handler creating duplicates. Stop installing that event handler more than once. Event handlers on the `socket` don't disappear just because the function they were installed in completes. They are still there. – jfriend00 Jun 15 '15 at 21:26
  • Ahh! I thought you ment the `emit` part! Let me change that and see what happens. Thanks – jfreak53 Jun 15 '15 at 21:34
  • 1
    @jfreak53 - can `.emit()` as many times as you want. That doesn't install an event handler, that just sends data. – jfriend00 Jun 15 '15 at 21:35