2016-06-24 203 views
0

我有簡單的nodejs應用程序與套接字,我遇到了一個錯誤,我找不到任何解決方案。所以我從應用程序發射到客戶端,並沒有發生。或者客戶端無法收到它 - 我不知道,因爲我無法檢查它是否成功地被客戶端接受。這是我當我試圖發出的調試回調的錯誤:nodejs不向客戶端發送數據

Error: Callbacks are not supported when broadcasting

這是我的應用程序代碼:

http.listen(6060, function() { 
    console.log("Listening on *: 6060"); 
}); 

io.set('authorization', function (handshakeData, accept) { 
    var domain = handshakeData.headers.referer.replace('http://', '').replace('https://', '').split(/[/?#]/)[0]; 

    if ('***' == domain) { 
     accept(null, true); 
    } else { 
     return accept('You must be logged in to take an action in this site!', false); 
    } 
}); 

io.use(function (sock, next) { 
    var handshakeData = sock.request; 
    var userToken = handshakeData._query.key; 

    if (typeof userToken !== null && userToken !== 0 && userToken !== '0' && userToken.length > 0) { 
     connection.query('***', 
      [xssfilter.filter(validator.escape(userToken))], 
      function (error, data) { 
       if (error) { 
        debug('Cant receive user data from database by token'); 
        next(new Error('Failed to parse user data! Please login!')); 
       } else { 
        // load data to this user. 
        _updateUsers(xssfilter.filter(validator.escape(userToken)), 'add', data[0], sock.id); 
        _loadPreData(); 

        next(null, true); 
       } 
      }); 
    } else { 
     debug('Cant receive user token'); 
     next(new Error('Failed to parse user data! Please login!')); 
    } 

    sock.on("disconnect", function() { 
     _updateUsers(false, 'remove', false, sock.id); 
    }); 
}); 

// we need to show people online count 
io.emit('online-count', { 
    count: Object.keys(connectedUsers).length 
}); 

和函數使用上述:

function _updateUsers(userToken, action, userData, sockedID) { 
    switch (action) { 
     case 'add': 
      connectedUsers[sockedID] = {...}; 
      io.emit('online-count', io.emit('online-count', { 
      count: Object.keys(connectedUsers).length 
     });); 

      break; 
     case 'remove': 
      delete connectedUsers[sockedID]; 
      io.emit('online-count', io.emit('online-count', { 
      count: Object.keys(connectedUsers).length 
     });); 

      break; 
    } 
} 

所以在發射後online-count我應該在客戶端接受它,因爲我在做:

var socket; 
socket = io(globalData.socketConn, {query: "key=" + globalData.userData.token}); 
socket.on('connect', function (data) { 
    console.log('Client side successfully connected with APP.'); 
}); 
socket.on('error', function (err) { 
    error('danger', 'top', err); 
}); 

socket.on('online-count', function (data) { 
    console.log('Got online count: ' + data.count); 
    $('#online_count').html(data.count); 
}); 

但問題出在這online-count ..沒有任何反應,它似乎不是從節點應用程序發送。有什麼建議麼?

回答

0

問題在於我的邏輯 - 我只在新用戶連接/斷開連接時才發送在線計數。問題通過添加函數來解決,每隔幾秒重複一次,並將在線計數發送到客戶端。

相關問題