简体   繁体   中英

Node.js server side connection to Socket.io

I have a Node.js application with a frontend app and a backend app, the backend will manage the list and "push" an update to the frontend app, the call to the frontend app will trigger a list update so that all clients receive the correct list data.

The problem is on the backend side, when I press the button, I perform an AJAX call, and that AJAX call will perform the following code (trimmed some operations out of it):

  Lists.findOne({_id: active_settings.active_id}, function(error, lists_result) {
      var song_list = new Array();
      for (i=0; i < lists_result.songs.length; i++) {
        song_list.push(lists_result.songs[i].ref);
      }
      Song.find({
        '_id': {$in: song_list}
      }, function(error, songs){
        // DO STUFF WITH THE SONGS
        // UPDATE SETTINGS (code trimmed)
        active_settings.save(function(error, updated_settings) {
            list = {
              settings: updated_settings,
            };
            var io = require('socket.io-client');
            var socket = io.connect(config.app_url);
            socket.on('connect', function () {
               socket.emit('update_list', {key: config.socket_key});
            });
            response.json({
                status: true,
                list: list
            });
            response.end();
          }
      });
    });

However the response.end never seems to work, the call keeps hanging, further more, the list doesn't always get refreshed so there is an issue with the socket.emit code. And the socket connection stays open I assume because the response isn't ended?

I have never done this server side before so any help would be much appreciated. (the active_settings etc exists)

I see some issues that might or might not be causing your problems:

  • list isn't properly scoped, since you don't prefix it with var ; essentially, you're creating a global variable which might get overwritten when there are multiple requests being handled;
  • response.json() calls .end() itself; it doesn't hurt to call response.end() again yourself, but not necessary;
  • since you're not closing the socket(.io) connection anywhere, it will probably always stay open;
  • it sounds more appropriate to not set up a new socket.io connection for each request, but just once at your app startup and just re-use that;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM