节点JS一对一消息

时间:2013-11-06 05:10:01

标签: javascript node.js

我在Node JS中创建了一个模块。我正在使用不同的Web浏览器将消息从一个用户推送到另一个用户。

在CMD控制台中,它正常工作并且正在发送消息。但它没有在客户页面上显示。

这是CMD输出:

enter image description here

以下是我的节点服务器代码:

var app                 = require('http').createServer(),
    io                  = require('socket.io').listen(app),
    fs                  = require('fs'),
    mysql               = require('mysql'),
    connectionsArray    = [],
    connection          = mysql.createConnection({
        host        : 'localhost',
        user        : 'admin',
        password    : 'admin',
        database    : 'test',
        port        : 3306
    }),
    POLLING_INTERVAL = 3000,
    pollingTimer;

// If there is an error connecting to the database
connection.connect(function(err) {
  // connected! (unless `err` is set)
  console.log( err );
});

// creating the server ( localhost:8000 )
app.listen(8000);



/*
*
* HERE IT IS THE COOL PART
* This function loops on itself since there are sockets connected to the page
* sending the result of the database query after a constant interval
*
*/

var pollingLoop = function () {

    // Doing the database query
    var query = connection.query('SELECT * FROM users'),
        users = []; // this array will contain the result of our db query

    // setting the query listeners
    query
    .on('error', function(err) {
        // Handle error, and 'end' event will be emitted after this as well
        console.log( err );
        forwardMessage( err );
    })
    .on('result', function( user ) {
        // it fills our array looping on each user row inside the db
        users.push( user );
    })
    .on('end',function(){
        // loop on itself only if there are sockets still connected
        if(connectionsArray.length) {
            pollingTimer = setTimeout( pollingLoop, POLLING_INTERVAL );

            //updateSockets({users:users});
        }
    });

};


// creating a new websocket to keep the content updated without any AJAX request
io.sockets.on( 'connection', function ( socket ) 
{
    console.log('Number of connections:' + connectionsArray.length);
    // starting the loop only if at least there is one user connected
    if (!connectionsArray.length) 
    {
        //pollingLoop();
    }
    socket.on('addUser', function (id) 
    {
        socket.id   = id;   
        console.log('Here I am. My User ID is: '+socket.id);
        socket.emit( 'notification' , 'ok' );   
    });



    socket.on('disconnect', function () 
    {
        var socketIndex = connectionsArray.indexOf( socket );
        console.log('socket = ' + socketIndex + ' disconnected');
        if (socketIndex >= 0) 
        {
            connectionsArray.splice( socketIndex, 1 );
        }
    });






    socket.on('sendMessage', function (message) 
    {
        console.log( 'Wow I got a New Message:'+message+' sent by: '+socket.id );

        socket.emit( 'notification' , message );
        //insertion in db
        // get concerned ids to pass notification
        var users = new Array();

        users.push('777');

        // call forwardMessage to send notifications...
        forwardMessage(users,message);

    });


    console.log( 'A new socket is connected!' );

    connectionsArray.push( socket );

});






var forwardMessage = function ( users, message ) 
{
    connectionsArray.forEach(function( userSocket )
    {
        if(inArray(userSocket.id,users))
        {
            userSocket.volatile.emit( 'notification' , message );

        }
    });


    function inArray(needle, haystack) // In_Array Function For Javascript
    {
        var length = haystack.length;

        for(var i = 0; i < length; i++) 
        {
            if(haystack[i] == needle) 
            return true;
        }
        return false;
    }
}

这是我的客户代码:

<script>
        // create a new websocket

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

            // on message received we print all the data inside the #container div
            socket.on('notification', function (data) 
            {
                //alert('got notification : '+data);
                $('#container').html('Got ');
            });


            socket.emit('addUser','<?php echo $_GET['id']; ?>');






        //----------------- SEND MESSAGE FUNCTION -------------------------//

        function sendMESSAGE()
        {
            var message = $("#message").val();
            socket.emit('sendMessage',message);
        }

    </script>

任何人都可以告诉我,我在这里做错了什么或在这里错过了什么?

0 个答案:

没有答案