0

Node Jsサーバーをセットアップしました。現在、データベースからすべてのユーザーのレコードを取得しています。

特定の Id の特定の User が必要な場合、それを Node Js に渡すにはどうすればよいですか?

例: PHP で行います: $_GET['id']; Node JSでも同じことが必要です。

ここに私のサーバーコードがあります:

var app                 = require('http').createServer(),
    io                  = require('socket.io').listen(app),
    fs                  = require('fs'),
    mysql               = require('mysql'),
    connectionsArray    = [],
    connection          = mysql.createConnection({
        host        : 'localhost',
        user        : 'root',
        password    : '',
        database    : 'test',
        port        : 3306
    }),
    POLLING_INTERVAL = 1000,
    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 );
        updateSockets( 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('disconnect', function () {
        var socketIndex = connectionsArray.indexOf( socket );
        console.log('socket = ' + socketIndex + ' disconnected');
        if (socketIndex >= 0) {
            connectionsArray.splice( socketIndex, 1 );
        }
    });
    socket.on('ddd', function (name) {
        socket.username=name;
    });


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

});

var updateSockets = function ( data ) {
    // adding the time of the last update
    data.time = new Date();
    // sending new data to all the sockets connected
    connectionsArray.forEach(function( tmpSocket ){
        tmpSocket.volatile.emit( 'notification' , data );
    });
};
4

1 に答える 1

1

まず、クライアント側の socket.io JavaScript を埋め込む必要があります。

script(rel="text/javascript" src="/js/libraries/socket.io.min.js");


次に、次のようにソケット サーバーに接続します。

var socket = io.connect("https://localhost:8080");


接続したら、イベントを発生させることができます。

button.on("click", function(){
    socket.emit("event-name", { userId : 2 });
});


サーバー側には、対応するリスナーがあります。

socket.on("event-name", function(data){
    console.log(data.userId); // logs: 2

    var query = // ...

    socket.emit("response", query);
});


クライアント側でも、応答を取得します。

socket.on("response", function(data){
    console.log(data); // logs: the query
});


エミットを受信するクライアントを決定するには、以下を参照してください。

socket.io ルームまたはネームスペース?

承認については、次を参照してください。

https://github.com/LearnBoost/socket.io/wiki/Authorizing

于 2013-11-05T12:03:42.170 に答える