简体   繁体   中英

How to emit from Client Side to a routes file with Socket.io in Node.js

So I'm using a singleton pattern to set up my websocket.

var sio = require('socket.io')
var io = null;

exports.io = function () {
  var socket; 
  if(io === null){ // Initialise if not already made 
    io = initialize(server);
  }
  return io;
};

exports.initialize = function(server) {

  io = sio.listen(server);
  var connections = [];

  console.log('IO Initialized!\n')

  io.on('connection', function(socket){
    connections.push(socket);
    console.log('Connected: %s sockets connected', connections.length);

    socket.on('disconnect', function(data){
      connections.splice(connections.indexOf(socket), 1);
      console.log('Disconnected: %s sockets connected', connections.length);
    });

    // Update function used to send messages to and from backend 
    socket.on('update', function(data){
      io.sockets.emit('new message', {msg: data});
    });


  });

};

And then in my public/javascript files I can call these like so

$(function(){

    var socket = io.connect();
    socket.emit('update', 'Test Update');
    socket.on('update', function(data){
       console.log('here: ' + data);
    });
});

and in my route file I have

router.use(function(req, res, next){
    if(socket === undefined){
        socket = io.io();
    }
    next();
});

router.get('/', function(req, res, next){


    socket.on('update', function(data){
        console.log('in routes');
    });

    socket.emit('update', 'leaving routes');
});

I can emit successfully from the routes file to the public js file (from back end to front end). However, I can't send information from the public js file to the routes file, it only sends to the singleton pattern js file. How can I get it to send to the routes file instead? If I'm going about this the wrong way could somebody please provide an exapmle of how to communicate between a route and a public js file?

As far as I can tell, there's nothing wrong with your singleton setup.

However , every place where you're going to be listening for events, you have to wrap it in io.on('connection', ...) . Making it a singleton doesn't prevent this from being a requirement.

Edit: I may be wrong here, I've just noticed that exports.initialize isn't actually returning connections . Tried 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