node.js server and client sideo code to connect

Problem

Im trying to set up a node.js server to send messages to the client, which will then display the messages using a jquery notification library, I'm using this notifcation library if anyone's interested: http://needim.github.com/noty/

At the minute I have a postgres database set up with a table which has a a trigger on it to write to a listener.

The trigger is as follows:

CREATE OR REPLACE FUNCTION new_noti() RETURNS trigger AS $$
DECLARE
BEGIN
    PERFORM pg_notify('watchers', TG_TABLE_NAME || ',msg,' || NEW.msg );
    RETURN new;
END; 
$$ LANGUAGE plpgsql;

Then I have a node.js server as follows:

var pg = require ('pg');

var pgConString = "pg://aydin:password@localhost/test"

var app = require('http').createServer(handler)
    , io = require('socket.io').listen(app)
    , url = require('url')

app.listen(8080);

function handler (request, respsonse) {
    var client = new pg.Client(pgConString);
    client.connect();
    client.query('LISTEN "watchers"');
    client.on('notification', function(msg) {
        console.log(msg.payload);
        sendMessage(msg.payload);
    });
}

function sendMessage(message) {
    io.sockets.emit('notification', {'message': message});
}

Then I have some client code as follows:

<script type="text/javascript">
    var socket = io.connect('http://localhost:8080');
    socket.on('notification', function (data) {
        console.log(data.message);
        newNoty(data);
    });

    function newNoty(data) {
        noty({
            "text":data.message,
            buttons: [{
                type: 'button green',
                text: 'Go to' 
            }],
            "theme":"noty_theme_twitter",
            "layout":"bottomRight",
            "type":"information",
            "animateOpen":{
                "height":"toggle"
            },
            "animateClose":{
                "height":"toggle"
            },
            "speed":500,
            "timeout":7500,
            "closeButton":true,
            "closeOnSelfClick":true,
            "closeOnSelfOver":false,
            "modal":false,
        });
    }
</script>

This doesn't work, it seems the node.js never receives the postgres notifications, I think this is because I am using the function handler and I'm not actually firing any requests to it from the client code. I'm not sure how to do this and whether it is the correct way? Is there a function on which can fire on connections and not requests?

And am I even doing it the right way round? should there be a server on the client side which node.js sends messages to? How does it know when a client is available? Any help or pointers to tutorials would be much appreciated. Thankyou.

Problem courtesy of: Aydin Hassan

Solution

You're not actually setting up your database connection until the client sends an HTTP request. It looks like that may never happen due to same-origin issues (your client code appears to be coming from somewhere other than the server you've shown).

In any case, you probably want to set up the connection in response to a "connection" event from io.sockets (i.e. move the stuff that's currently in the HTTP request handler there). That's how it "knows when a client is available". Or maybe you should be doing it as part of initialization. Your client-side code seems OK, but it's out of context so it's hard to tell whether it really fits your needs.

Solution courtesy of: ebohlman

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.