I am new in WebSocket's so I am trying to Make an application that uses WebSocket's to Update in Realtime. Here is my code:
const PORT = process.env.PORT || 3000;
const INDEX = "./index.html";
const socketIO = require("socket.io");
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.sendFile(INDEX, { root: __dirname });
});
app.listen(PORT, () => {
console.log("SERVER LISTENING ON PORT http://localhost:3000");
});
const io = socketIO(app);
io.on("connection", (socket) => {
console.log("Client connected");
socket.on("disconnect", () => console.log("Client disconnected"));
});
This code throws Error As follows:
Error: You are trying to attach socket.io to an express request handler function. Please pass a http.Server instance.
But when I write the code as follows:
const PORT = process.env.PORT || 3000;
const INDEX = "/index.html";
const socketIO = require("socket.io");
const express = require("express");
const server = express()
.get("/", (req, res) => res.sendFile(INDEX, { root: __dirname }))
.use("/static", express.static("static"))
.listen(PORT, () => console.log(`Listening on ${PORT}`));
const io = socketIO(server);
io.on("connection", (socket) => {
console.log("Client connected");
socket.on("disconnect", () => console.log("Client disconnected"));
});
It simply Works.
Please Help me What is happening here.
Thank you in advance!!!
CodePudding user response:
socket.io is expecting an instance returned from the app.listen method (where app is an express instance)
At 1st piece of code , you are passing an express instance which is wrong as I mentioned above
The fix for 1st piece of code , so you can understand it better
const PORT = process.env.PORT || 3000
const INDEX = './index.html'
const socketIO = require('socket.io')
const express = require('express')
const app = express()
const server = app.listen(PORT, () => {
console.log('SERVER LISTENING ON PORT http://localhost:3000')
})
const io = socketIO(server)
app.get('/', (req, res) => {
res.sendFile(INDEX, { root: __dirname })
})
io.on('connection', (socket) => {
console.log('Client connected')
socket.on('disconnect', () => console.log('Client disconnected'))
})