使用nodejs使Socket和rest协同工作



当前我正在使用"套接字.io";包,并且我想在rest调用中访问IO实例。

以下是我尝试过的代码。

index.js

const app = express();
const newServer = require('http').Server(app);
const { Server } = require('socket.io');
const io = new Server(newServer);
app.use("/restApiCall", require("./apis"));
newServer.listen(8002, () => {
console.log(`Server listening to port 8002`);
});

apis.js

const express = require("express");
const router = express.Router(); 
const SubmoduleController = require("./controllers/subModule.js");
router.route('/abc').post(SubmoduleController.updateAbc);

subModule.js

module.exports = {
updateAbc: async function (req, res, next) {
/*** Here i want access my socket IO instance and emit message to UI
}
}

我该如何做到这一点。由于IO实例是index.js的一部分,因此rest api是在不同的文件中编写的。如何传递实例?

如果您想同时使用socket.io和express服务器(用于REST API(,您应该在两个不同的端口上侦听。

最新更新