NodeJS 如何导出socket.io函数

uemypmqf  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(124)

伙计们,我有一个基本的套接字连接,我想在测试请求后向客户端发送消息。我尝试了正常的导出和eventemitter,但无法管理它

//this is server.js file
const express = require("express");
const testRoutes = require("./routes/testRoutes");

const app = express();
  
//Socket.io connection
const server = require("http").createServer(app);
const io = require("socket.io")(server, {
  cors: {
    origin: "http://localhost:3000",
    methods: ["GET", "POST"],
  },
});

//Socket.io communication
io.on("connection", (socket) => {
  console.log("socket on");
  socket.on("newMessageToServer", ({ message, username }) => {
    console.log("messagefromclient", message, username);
    io.emit("newMessageToClient", { message, username }); //<-- i want to reach this line from another file
  });
});

//Routes
app.use("/test", testRoutes);

//Server
const port = process.env.port || 5000;
server.listen(port, () => {
  console.log("listening " + port);
});

字符串
所以我想在点击下面的/test/test端点后向客户端发送一条消息

//this is testRoutes.js file
const express = require("express");
const router = express.Router();

router.post("/test", async (req, res) => {
  console.log("testsocket");
  // -- I want to use socket here like this
  //io.emit("newMessageToClient", { message, username });
});

module.exports = router;

e5njpo68

e5njpo681#

让你的testRoutes导出一个接受io接口并返回路由器的函数。例如

// testRoutes.js

module.exports = (io) => {
  const router = express.Router();

  router.post("/test", async (req, res) => {
    console.log("testsocket");
    io.emit("newMessageToClient", { /* whatever */ });
    res.sendStatus(202); // Accepted
  });

  return router;
};

字符串
然后在server.js文件中使用它

app.use("/test", testRoutes(io));

相关问题