Link to home
Start Free TrialLog in
Avatar of Nathan Riley
Nathan RileyFlag for United States of America

asked on

node.js and socket.io help

I'm trying to figure out how to pass custom variables from the one script to the other.

So my script that users hit:
<html>
<body>
<h1>Simple Page</h1>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
    var socket = io.connect('http://node.domain.com:8000', {orgID:'abc'});
    socket.on('connect', function () {

      socket.send(window.location);
    });
</script>
</body>
</html>

Open in new window


You will see I'm trying to pass a custom orgID.  Not sure if this is correct.

Then my server.js looks like this, how do I set it into a variable there? Right now it just shows undefined for it in console.

var io = require('socket.io').listen(8000);
var mysql      = require('mysql');
var con = mysql.createConnection({
    host     : 'localhost',
    user     : 'user',
    password : 'asdf_user',
    database : 'asdf_dev'
});

con.connect(function(err){
    if(err){
        console.log('Error connecting to Db');
        return;
    }
    console.log('Connection established');
});

io.sockets.on('connection', function (socket) {

    socket.on('message', function (message) {
        console.log("Got message: " + message);
        console.log(socket.handshake.orgID);
        var ip = socket.handshake.address;
        url = message;
        //io.sockets.emit('pageview', { 'url': message, 'ip': ip });
        io.sockets.emit('pageview', { 'url': url, 'timestamp': new Date(), 'ip': ip});


        var post  = {pageName: url.pathname, ip: ip};
        con.query('INSERT INTO analytics SET ?', post, function(err, res) {
            if(err) throw err;
        });
    });
});

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of James Bilous
James Bilous
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial