【问题标题】:Socket.io messaging app not sending messages with express serverSocket.io 消息传递应用程序不使用快速服务器发送消息
【发布时间】:2021-08-20 18:38:36
【问题描述】:

我正在使用 socket.io 和 React 前端构建消息传递功能。使用仅 socket.io 的服务器,它按预期工作,代码如下:

仅限 Socket.io 服务器

const io = require("socket.io")(5000, {
    cors: {
        origin: "http://localhost:3000",
        methods: ["GET", "POST"],
    },
});

io.on("connection", (socket) => {
    const id = socket.handshake.query.id;
    socket.join(id);

    socket.on("send-message", ({ recipients, text }) => {
        recipients.forEach((recipient) => {
            const newRecipients = recipients.filter((r) => r !== recipient);
            newRecipients.push(id);
            socket.broadcast.to(recipient).emit("receive-message", {
                recipients: newRecipients,
                sender: id,
                text,
            });
        });
    });
});

我正在尝试与 express 集成。服务器从下面的代码开始,但消息不再起作用:

快递服务器

const express = require("express");
const socketIo = require("socket.io");
const cors = require("cors");

const PORT = process.env.PORT || 5000;
const app = express();

const http = app.listen(PORT, () =>
    console.log(`???? Server ready at http://localhost:${PORT}`)
);

const io = socketIo(http, {
    cors: {
        origin: "http://localhost:3000",
        methods: ["GET", "POST", "send-message", "receive-message"],
    },
});

io.once("connection", (socket) => {
    const id = socket.handshake.query.id;
    socket.join(id);

    socket.on("connect_error", (err) => {
        console.log(`connect_error due to ${err.message}`);
    });

    socket.on("send-message", ({ recipients, text }) => {
        recipients.forEach((recipient) => {
            const newRecipients = recipients.filter((r) => r !== recipient);
            newRecipients.push(id);
            socket.broadcast.to(recipient).emit("receive-message", {
                recipients: newRecipients,
                sender: id,
                text,
            });
        });
    });
});

在 Chrome 中的两个实例本地运行它,并在 localhost:3000 上打开一个窗口和另一个隐身窗口

【问题讨论】:

  • 请为您的最终目标添加更多解释,以及实际的错误或问题是什么。

标签: node.js express sockets socket.io messaging


【解决方案1】:

如所述here on('connection') 客户端事件不起作用。改成on('connect');

// server-side
io.on("connection", (socket) => {
  console.log(socket.id); // x8WIv7-mJelg7on_ALbx
});

// client-side
socket.on("connect", () => {
  console.log(socket.id); // x8WIv7-mJelg7on_ALbx
});

【讨论】:

    猜你喜欢
    • 2012-03-04
    • 1970-01-01
    • 2014-03-16
    • 2012-08-04
    • 2021-06-19
    • 2013-01-11
    • 1970-01-01
    • 2019-01-21
    • 2019-01-16
    相关资源
    最近更新 更多