NodeJS 为什么套接字io显示未找到错误?

qyuhtwio  于 2023-01-08  发布在  Node.js
关注(0)|答案(2)|浏览(175)

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"

    • 应用程序. 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 };
    • 聊天句柄. 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("client connected");
})

ljo96ir5

ljo96ir51#

如果您的原始代码是这样开始的:

node app.js

然后,一个问题是chatHandle.js代码永远不会加载或运行。所以,你永远不会得到一个Socket.io服务器连接到你的http服务器。
看起来你可以通过改变你的启动来解决这个问题:

node chatHandle.js

因为chatHandle.js会加载app.js。按照当前的代码组织方式,您不能只从app.js加载chatHandle.js,因为这会创建一个循环依赖关系,其中chatHandle.js加载app.jsapp.js加载chatHandle.js
我更喜欢的结构是从app.js加载chatHandle.js,但是让chatHandle.js在加载时不做任何初始化。相反,导出一个socketioInit()函数,然后从app.js调用它,并将server示例传递给它,这样它就可以socket.io使用该服务器设置www.example.com。这就形成了你的套接字。完全独立于服务器的创建,并且可以在不同地设置HTTP服务器的不同项目中使用。

yjghlzjz

yjghlzjz2#

    • 应用程序. 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}`);
});
    • 手柄. 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 };
    • 客户端. js**
const socket = io("/chat");
socket.on("connect",()=>{
    console.log("client connected");
})

相关问题