Socket IO为什么显示未找到错误?

huangapple go评论71阅读模式
英文:

Why socket io is showing not found error?

问题

我正在尝试学习如何在我的项目中使用socket.io进行私人聊天。
在我的后端,我正在使用Node和Express,并在路由"/chat"上发送聊天页面。

app.js

import http from "http";
import express from "express";
import bodyParser from "body-parser";
import cookieParser from "cookie-parser";
import dotenv from "dotenv";
import { router } from "./routes/web.js";
import { connectDb } from "./db/connectDb.js";
// 配置dotenv
dotenv.config();

// 初始化应用程序
const app = express();
// 服务器
const node__server = http.createServer(app);

// 静态文件
app.use(express.static('../frontend'));

// 中间件
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());

// 加载路由
app.use("/", router);

// 定义模板引擎
app.set("view engine", "ejs");

// 连接数据库
connectDb(process.env.DATABASE_URL);

// 监听浏览器端口
node__server.listen(process.env.PORT, () => {
    console.log(`App is listening at http://localhost:${process.env.PORT}`);
});

export { node__server };

chatHandle.js

import { Server } from "socket.io";
import { node__server } from "./app";
// socket 
const io = new Server(node__server);

io.of("/chat").on("connection", (socket) => {
    console.log(socket.id);
})

在client.js中(聊天页面的脚本)

const socket = io("/chat");
socket.on("connect", () => {
    console.log("客户端已连接");
})
英文:

I am trying to learn socket.io for private chat in my project
In my backend i am using node and express and sending chat page on route "/chat"

app.js

import http from "http";
import express from "express";
import bodyParser from "body-parser";
import cookieParser from "cookie-parser";
import dotenv from "dotenv";
import { router } from "./routes/web.js";
import { connectDb } from "./db/connectDb.js";
// configuring dotenv
dotenv.config();

// initialize app
const app = express();
// server
const node__server = http.createServer(app);

// static files
app.use(express.static('../frontend'));

// middlewares
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());

// load routes
app.use("/", router);

// define template engine
app.set("view engine", "ejs");

// connecting database
connectDb(process.env.DATABASE_URL);

// Listening to browser port
node__server.listen(process.env.PORT, () => {
    console.log(`App is listening at http://localhost:${process.env.PORT}`);
});

export { node__server };

chatHandle.js

import { Server } from "socket.io";
import { node__server } from "./app";
// socket 
const io = new Server(node__server);

io.of("/chat").on("connection", (socket) => {
    console.log(socket.id);
})

in client.js (script of chat page)

const socket = io("/chat");
socket.on("connect",()=>{
    console.log("client connected");
})

Socket IO为什么显示未找到错误?

答案1

得分: 1

如果您正在使用以下方式启动您的原始代码:

node app.js

那么存在一个问题,即chatHandle.js代码从未被加载或运行。因此,您永远无法将Socket.io服务器附加到您的HTTP服务器上。

看起来您可以通过将启动方式更改为以下方式来修复这个问题:

node chatHandle.js

因为chatHandle.js会加载app.js。按照您当前的代码组织方式,您无法从app.js中直接加载chatHandle.js,因为这将创建一个循环依赖,其中chatHandle.js加载app.js,而app.js加载chatHandle.js

我建议的结构是从app.js加载chatHandle.js,但是在加载时不执行任何初始化操作。相反,导出一个socketioInit()函数,然后从app.js中调用该函数,并将server实例传递给它,以便它可以使用该服务器设置socket.io。这样,您的socket.io与服务器的创建完全独立,可以在不同的项目中使用,该项目以不同的方式设置HTTP服务器。

英文:

If you are starting your original code with this:

node app.js

Then, a problem is that the chatHandle.js code is never loaded or run. So, you never get a Socket.io server attached to your http server.

It appears you could fix that by just changing your startup to:

node chatHandle.js

because chatHandle.js loads app.js. The way your code is currently organized, you can't just load chatHandle.js from app.js because that would create a circular dependency where chatHandle.js loads app.js and app.js loads chatHandle.js.

My preferred structure would to be load chatHandle.js from app.js, but have chatHandle.js not do any initialization on load. Instead, export a socketioInit() function and then call that from app.js and pass it the server instance so it can then set up socket.io using that server. This makes your socket.io completely independent from the creation of the server and it could be used in a different project that sets up the http server differently.

答案2

得分: 0

以下是您要翻译的代码部分:

app.js

import http from "http";
import express from "express";
import bodyParser from "body-parser";
import cookieParser from "cookie-parser";
import dotenv from "dotenv";
import { router } from "./routes/web.js";
import { connectDb } from "./db/connectDb.js";
import { Server } from "socket.io";
import { chatManage } from "./chathandle.js";
// 配置 dotenv
dotenv.config();

// 初始化应用程序
const app = express();
// 服务器
const node__server = http.createServer(app);

// 静态文件
app.use(express.static('../frontend'));

// 中间件
// extended 为 true 允许具有嵌套值,false 阻止嵌套值
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());

// 加载路由
app.use("/", router);

// 定义模板引擎
app.set("view engine", "ejs");

// 连接数据库
connectDb(process.env.DATABASE_URL);

// socket
const io = new Server(node__server);
// 监听聊天请求
io.of("/chat").on("connection", (socket) => {
    chatManage(socket);
});

// 监听浏览器端口
node__server.listen(process.env.PORT, () => {
    console.log(`应用程序正在监听 http://localhost:${process.env.PORT}`);
});

chathandle.js

function chatManage(socket) {
    console.log("从服务器的 socket id 是", socket.id);

    socket.on("message", (msg) => {
        // socket.broadcast.emit(eventName, dataObject)
        socket.broadcast.emit("message", msg);
    });
    socket.on("success", (msg) => {
        console.log(msg.message, msg.id);
    });
    socket.on("failed", (msg) => {
        console.log(msg.message, msg.id);
    });
}

export { chatManage };

client.js

const socket = io("/chat");
socket.on("connect", () => {
    console.log("客户端已连接");
});
英文:

app.js

import http from "http";
import express from "express";
import bodyParser from "body-parser";
import cookieParser from "cookie-parser";
import dotenv from "dotenv";
import { router } from "./routes/web.js";
import { connectDb } from "./db/connectDb.js";
import { Server } from "socket.io";
import { chatManage } from "./chathandle.js";
// configuring dotenv
dotenv.config();

// initialize app
const app = express();
// server
const node__server = http.createServer(app);

// static files
app.use(express.static('../frontend'));

// middlewares
// extented true allows to have nested valuse and false prvents this                         
nested valuess
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());

// load routes
app.use("/", router);

// define template engine
app.set("view engine", "ejs");

// connecting database
connectDb(process.env.DATABASE_URL);

// socket
const io = new Server(node__server);
// listen chat request
io.of("/chat").on("connection", (socket) => {
    chatManage(socket);
});

// Listening to browser port
node__server.listen(process.env.PORT, () => {
    console.log(`App is listening at             
    http://localhost:${process.env.PORT}`);
});

chathandle.js

function chatManage(socket) {
    console.log("From server socket id is ", socket.id);

        socket.on("message", (msg) => {
            // socket.broadcast.emit(eventName,dataObject)
            socket.broadcast.emit("message", msg);
        })
        socket.on("success", (msg) => {
            console.log(msg.message, msg.id);
        })
        socket.on("failed", (msg) => {
            console.log(msg.message, msg.id);
        })
}

export { chatManage };

client.js

const socket = io("/chat");
socket.on("connect",()=>{
    console.log("client connected");
})

huangapple
  • 本文由 发表于 2023年1月7日 01:36:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75034284.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定