Use socket.io in controllers

后端 未结 3 1208
离开以前
离开以前 2021-01-30 00:37

I only need socket.io to emit messages to clients, if a new object is inserted to database. So my idea was to emit the message directly fr

3条回答
  •  梦谈多话
    2021-01-30 01:00

    You can do this very easily you have to only write socket connection in app.js and than you can use socket anywhere you want

    In app.js file put code like below

     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;
    

    In any file or in controller you can import that object like below

     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 ?");
    

提交回复
热议问题