1

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

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

这是 CMD 输出:

在此处输入图像描述

这是我的节点服务器代码:

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>

谁能告诉我我在这里做错了什么或错过了什么?

4

0 回答 0