控制器上的 Socket.IO [英] Socket.IO on controller

查看:26
本文介绍了控制器上的 Socket.IO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对套接字非常陌生,我一直在努力实现我在网上看到的一些文档.这是我目前的设置,我想仅针对 healthcheck api 端点 (/api/v1/healthcheck) 运行 socket.io 我将如何在 healthcheck 控制器中运行 socket io?并对响应发出更改?任何帮助表示赞赏,我正在撕掉我的头发:(

I'm pretty new to sockets and I've been struggling to implement some of the documentation i've seen online. This is my set up currently and I wanted to run socket.io against just the healthcheck api endpoint (/api/v1/healthcheck) how would I go about running socket io in the healthcheck controller? and emit changes to the response? Any help is appreciated, i'm tearing my hair out :(

Server.js

const socket = require('socket.io')

const healthcheck = require('./routes/healthcheck');
const auth = require('./routes/auth');
const users = require('./routes/users');

const server = app.listen(
  PORT,
  console.log(
    `Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.cyan.bold
  )
);

let io = require('socket.io')(server);
app.set("io", io);

//Auth
app.use('/api/v1/auth', auth);
app.use('/api/v1/users', users);  
//Health check
app.use('/api/v1/healthcheck', healthcheck);

/routes/healthcheck.js

const express = require('express');
const { checkHealth } = require('../controllers/healthcheck');

const router = express.Router();

router.post('/', checkHealth);

module.exports = router;

/controllers/healthcheck.js

const asyncHandler = require('../middleware/async');

exports.checkHealth = asyncHandler(async (req, res, next) => {
    res.status(200).json({
        success: true,
        data: {
            status: "Alive!"
        }
    });
});

推荐答案

您可以将 io 的实例传入该健康检查路由,然后只需侦听事件并采取行动.示例代码如下.

You can pass in the instance of io into that healthcheck route and then simply listen to events and take action. Sample code below.

server.js

const socket = require('socket.io')

const server = app.listen(
  PORT,
  console.log(
    `Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.cyan.bold
  )
);

let io = require('socket.io')(server);
app.set("io", io);

// pass in io to the relevant route
const healthcheck = require('./routes/healthcheck')(io);
const auth = require('./routes/auth');
const users = require('./routes/users');

//Auth
app.use('/api/v1/auth', auth);
app.use('/api/v1/users', users);  
//Health check
app.use('/api/v1/healthcheck', healthcheck);

健康检查路线

const express = require('express');
const { checkHealth } = require('../controllers/healthcheck');

const router = express.Router();

module.exports = (io) => {
   router.post('/', checkHealth);

   io.on('connection', socket => {
      socket.emit('hello', {message: 'helloworld'});

      socket.on('reply', checkHealth.someMethod); 
   });

   return router;
}

我宁愿在文件中创建端点 - 与您为快速路由所做的一样,并在您的 server.js 中按如下方式初始化这些:

I would rather create endpoints in files - same as you do for express routes, and init these in your server.js as follows:

let io = require('socket.io')(server);
app.set("io", io);

io.on('connection', socket => {
   require('./myendpointexample')(socket);
});

myendpointexample.js

module.exports = (socket) => {
   socket.on('myevent', (message) => {
      mycontroller.myFunction(message).then(result => {
          socket.emit('myEvent', result);
      });
   });
};

这篇关于控制器上的 Socket.IO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆