23

如果将新对象插入数据库,我只需socket.io要向emit发送消息。clients所以我的想法是直接从控制器的insert-method. 在我的server.js文件中,我正在创建socket.io object并尝试使其可用于其他模块:

var server = require('http').createServer(app);
var io = require('socket.io').listen(server);

//make socket io accessible for other modules
module.exports.io = io;

在我的控制器中,我尝试以这种方式使用 socket.io:

var io = require('../server').io;
...
io.sockets.on("connection", function(socket){
  passportSocketIo.filterSocketsByUser(io, function (user) {
    return user.workingAt === socket.handshake.user.workingAt;
  }).forEach(function(s){
    s.send("news", insertedObject);
  });
});

在这里我被困住了。"connection" 事件永远不会被触发,因此不会发出消息。socket.io这是在separate文件中使用的正确方法吗?不幸的是我找不到复杂socket.io的例子。

4

3 回答 3

55

您正在尝试反转控制流程。这样做的方法是让您的控制器实现一个接口(API),您的服务器可以使用该接口将控制权传递给。

一个简单的例子是:

mycontroller.js

// no require needed here, at least, I don't think so

// Controller agrees to implement the function called "respond"
module.exports.respond = function(socket_io){
    // this function expects a socket_io connection as argument

    // now we can do whatever we want:
    socket_io.on('news',function(newsreel){

        // as is proper, protocol logic like
        // this belongs in a controller:

        socket.broadcast.emit(newsreel);
    });
}

现在在server.js

var io = require('socket.io').listen(80);
var controller = require('./mycontroller');

io.sockets.on('connection', controller.respond );

这个例子很简单,因为控制器 API 看起来很像 socket.io 回调。但是如果你想将其他参数传递给控制器​​呢?像io对象本身还是代表端点的变量?为此,您需要做更多的工作,但这并不多。这与我们经常用来打破或创建闭包的技巧基本相同:函数生成器:

mycontroller.js

module.exports.respond = function(endpoint,socket){
    // this function now expects an endpoint as argument

    socket.on('news',function(newsreel){

        // as is proper, protocol logic like
        // this belongs in a controller:

        endpoint.emit(newsreel); // broadcast news to everyone subscribing
                                     // to our endpoint/namespace
    });
}

现在在服务器上,我们需要做更多的工作才能通过终点:

var io = require('socket.io').listen(80);
var controller = require('./mycontroller');

var chat = io
  .of('/chat')
  .on('connection', function (socket) {
      controller.respond(chat,socket);
  });

请注意,我们直接通过,但我们通过闭包socket捕获。chat有了这个,您可以拥有多个端点,每个端点都有自己的控制器:

var io = require('socket.io').listen(80);
var news_controller = require('./controllers/news');
var chat_controller = require('./controllers/chat');

var news = io
  .of('/news')
  .on('connection', function (socket) {
      news_controller.respond(news,socket);
  });

var chat = io
  .of('/chat')
  .on('connection', function (socket) {
      chat_controller.respond(chat,socket);
  });

实际上,您甚至可以为每个端点使用多个控制器。请记住,控制器除了订阅事件之外什么都不做。正在监听的是服务器:

var io = require('socket.io').listen(80);
var news_controller = require('./controllers/news');
var chat_controller = require('./controllers/chat');

var chat = io
  .of('/chat')
  .on('connection', function (socket) {
      news_controller.respond(chat,socket);
      chat_controller.respond(chat,socket);
  });

它甚至适用于普通的 socket.io(无端点/命名空间):

var io = require('socket.io').listen(80);
var news_controller = require('./controllers/news');
var chat_controller = require('./controllers/chat');

io.sockets.on('connection', function (socket) {
    news_controller.respond(socket);
    chat_controller.respond(socket);
});
于 2013-10-24T08:04:17.433 回答
1

你可以很容易地做到这一点,你只需要在 app.js 中编写套接字连接,然后你就可以在任何你想要的地方使用套接字

app.js文件中放入如下代码

 var http = require('http').createServer(app);
 const io = require('socket.io')(http);  

 io.sockets.on("connection", function (socket) {
 // Everytime a client logs in, display a connected message
 console.log("Server-Client Connected!");

 socket.join("_room" + socket.handshake.query.room_id);

 socket.on('connected', function (data) {

   });
});

const socketIoObject = io;
module.exports.ioObject = socketIoObject;

在任何文件或控制器中,您可以像下面这样导入该对象

 const socket = require('../app'); //import socket  from app.js

      //you can emit or on the events as shown 
 socket.ioObject.sockets.in("_room" + req.body.id).emit("msg", "How are You ?");
于 2020-10-09T09:05:08.793 回答
-1
You can solve this problem declaring io instance as global variable.

at the last line of my app.js: IoInstance = require("./socket.io")(server);

at the './socket.io' :
const chatNamespace = require("./namespaces/chat");
const notificationsNamespace = require("./namespaces/notifications");
const auth = require("./middlewares/auth");

module.exports = (server) => {
  const io = require("socket.io").listen(server);

  io.of("/chats")
    .use(auth)
    .on("connect", (socket) => chatNamespace({ io, socket }));

  io.of("/notifications")
    .use(auth)
    .on("connect", (socket) => notificationsNamespace({ io, socket }));

  return io;
};

then, you can use the IoInstance wherever you want, event into your controller. Btw, I could have use it into my namespaces as well, but I've just realized it right now.

example of implementation in the testController.js:

module.exports = async (req, res) => {
  IoInstance.of("/notifications")
    .to("myUserId")
    .emit("sendNotification", ["test", "test1"]);
  return res.send("oioi");
};
于 2020-11-14T04:13:50.113 回答