Socket.io 客户端没有监听事件

Socket.io Not listening event on client side

我正在使用 socket.io 的官方代码示例并试图了解它是如何工作的。

事件正在服务器端触发和接收,但客户端未侦听该事件。

服务器我 运行 在 node.js 端口 3000 和

客户端我是 运行 VSCode 端口 5500 上的 GoLive 扩展

这是我的详细代码

Package.json

{
  "name": "socket-chat-example",
  "version": "0.0.1",
  "description": "my first socket.io app",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "socket.io": "^4.1.2"
  },
  "scripts": {
    "start": "DEBUG=* nodemon index.js"
  },
  "devDependencies": {
    "nodemon": "^2.0.15"
  }
}

Index.html(由于 Whosebug 的限制,我无法粘贴整个页面代码这里只有主体代码,没有 css)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.socket.io/4.4.1/socket.io.min.js"></script>

<ul id="messages"></ul>
<div id="form">
  <input id="input" autocomplete="off" />
  <button id="btn_submit">Send</button>
</div>

<script>
  $(function () {
    var socket = io("http://localhost:3000");
    socket.on("connect", function () {
      console.log("client is connected", socket.connected);
      socket.emit("message", "Welcome To Chat");
    });
    var messages = document.getElementById("messages");
    var input = document.getElementById("input");

    $("#btn_submit").on("click", function () {
      if (input.value) {
        console.log(input.value);
        socket.emit("message", input.value, (response) => {
          console.log(response); // "got it"
        });
        input.value = "";
      }
    });
    console.log(socket);
    socket.on("message", function (msg) {
      console.log(msg);
      var item = document.createElement("li");
      item.textContent = msg;
      messages.appendChild(item);
      window.scrollTo(0, document.body.scrollHeight);
    });
  });
</script>

index.js

const app = require('express')();
var cors = require('cors');
const http = require('http').Server(app);
const io = require('socket.io')(http, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  }
});
const port = process.env.PORT || 3000;

app.use(cors())
const connections = [];

io.on('connection', (socket) => {
  connections.push(socket);
  console.log(" %s sockets is connected", connections.length);

  socket.on("disconnect", () => {
    connections.splice(connections.indexOf(socket), 1);
    console.log("Now %s sockets is connected", connections.length);
  });
});

http.listen(port, () => {
  console.log(`Socket.IO server running at http://localhost:${port}/`);
});

在您的 index.js 文件中,您已经初始化了套接字,但我看不到任何事件接收或发出方法。 您应该在服务器端使用 socket.emit() 将数据发送到客户端,并使用 socket.on() 从客户端接收数据。您应该从 index.js 文件发送 socket.emit("message", "Message") 。 你可以找到更好的解释 here.