//module declaration
const express = require("express"),
bd = require("body-parser"),
cors = require("cors"),
http = require("http");
const app = express();
const server = http.createServer(app);
const socket = require("socket.io")(server);
//middleware
const corsOptions = {
credentials: true,
origin: ["*"],
};
app.use(bd.json());
app.use(bd.urlencoded({ extended: true }));
app.use(cors(corsOptions));
//io declaration
const io = socket(
server.listen(5050, (err) => {
if (err) throw err;
else console.log("successfully connected");
})
);
//routing
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
//websocket configuration
io.on("connection", (socket) => {
console.log("succesfully connected", socket.id);
socket.on("btn", (data) => {
io.socket.emit("btn", data);
console.log(data);
});
});
I used require("socket.io)(server)
method but this method seems to arising a problem. When I run the app.js, it says socket is not a function.
I tried using websocket for communication between client side and server side. Now I am simply trying to detect a keypress from html in node js but when I use require("socket.io")(server) socket is a function problem arises.
require("socket.io")
indeed does not return a function - you're probably looking for the Server
class under it, that should be instantiated with new
:
const socket = new require("socket.io").Server(server);