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");
})
CodePudding user response:
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.
CodePudding user response:
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");
})