doubi9615 2015-02-18 15:01
浏览 55

NodeJS在没有客户请求的情况下发送请求

i'm newbie in nodejs and i want to send data to client without send request from client, for example i want to after create new data in database like with mysql trigger nodjs fetch data from database and send necessary data to client. in other language programing we try to create Thread to fetch such as database or send JSON object every one secode, how to this ability in NodeJS?

var server   = require('http').createServer(),
    io    = require('socket.io').listen(server),
    mysql = require('mysql'),
    express =   require('express'),
    fs    = require('fs');

server.listen(3000, 'localhost');
console.log("connected...");
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'node'
});

io.listen(server).on('connection', function(client) {
    /* FETCH DATA IF NECESSERY AND IF DATA INSERTED IN DB OR UPDATE OR DELETE*/
    console.log("data send");

});
  • 写回答

1条回答 默认 最新

  • doudao5287 2015-02-18 16:10
    关注

    The rule is: When the client connects to the server, you store the identifier of the connection (for future use)
    When a specific event occurs on the server side and want to transmit information to the client, fastening the stored credentials
    With Socket Web, the server does not require that the client starts the communication (as long as the connection is maintained by the server and the client)

    You can do as follow :

        // it can be 2 dimensional array USER_ID, SOCKET
        var STORED_SOCKET = new Array () ;
    
        // ...
        io.listen(server).on('connection', function (client) {
            /* FETCH DATA IF NECESSERY AND IF DATA INSERTED IN DB OR UPDATE OR DELETE*/
            STORED_SOCKET.push( client) ;
            console.log("data send");
    
        });
    
        // -- if something happend in mysql, you browse your STORED_SOCKET array, find the concerned user and send him data
        function mysqlEvent (userId, yourData) {    
            for ( i = 0 ; i < STORED_SOCKET.length ; i++ ) {
                if (STORED_SOCKET[i]['USER_ID'] == userId) {
                    STORED_SOCKET[i].volatile.emit( yourData ) ;
                }
            }
        }
    

    Hope it is clear :)

    评论

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示