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:
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