简体   繁体   English

如何在Node.js中使用Socket.io从客户端发出到路由文件

[英]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. 因此,我使用单例模式来设置我的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 然后在我的public / javascript文件中,我可以这样称呼它们

$(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). 我可以成功地将路由文件发送到公共js文件(从后端到前端)。 However, I can't send information from the public js file to the routes file, it only sends to the singleton pattern js file. 但是,我无法将信息从公共js文件发送到路由文件,而只能发送到单例模式js文件。 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? 如果我使用的是错误的方式,请问有人可以提供路线与公共js文件之间如何通信的示例吗?

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', ...) . 但是 ,在要监听事件的每个地方,都必须将其包装在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 . 编辑:我可能在这里错了,我刚刚注意到exports.initialize实际上并没有返回connections Tried that? 试过了吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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