在客户端调用内部函数时,Socket io 发出不起作用

问题描述 投票:0回答:1

我在套接字 io 简单运行方面遇到问题。 连接已成功建立,当我尝试从客户端发出消息时出现问题。 emit 方法仅在位于函数外部或连接调用内部时才有效。 在单击触发器之后的附加示例代码中, func 方法将运行,但是,仅当我将其放在任何函数之外时,emit 语句才起作用 有谁知道为什么吗?

客户:

const socket = io("http://localhost:3001")
  const func = () => {
    socket.emit("send_message", "hello")
  }

     <button onClick={func}>SEND</button>

服务器:

 const { createServer } = require('http')
    const { Server } = require('socket.io')
    const httpServer = createServer();



    const io = new Server(httpServer, {
      cors: {
        origin: "http://localhost:3000/chat",
      },
    methods: ["GET", "POST"]
    });

    io.on("connection", (socket) => {

       socket.on("send_message", (...args) => {
        console.log(args)
    });

     })



    httpServer.listen(3001, () => {
    console.log("server is running");
    });
next.js socket.io
1个回答
0
投票

您检查过套接字是否在全局范围内吗?有时调用“func”函数时它会被重置

© www.soinside.com 2019 - 2024. All rights reserved.