io.on('connection', socket =>{ ^
TypeError: io.on is not a function at Object. (D:\shalini course\projects\chat app\nodeserver\nodeapp.js:7:4) at Module._compile (node:internal/modules/cjs/loader:1218:14) at Module._extensions..js (node:internal/modules/cjs/loader:1272:10) at Module.load (node:internal/modules/cjs/loader:1081:32) at Module._load (node:internal/modules/cjs/loader:922:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:23:47
it shows this error when I run a cmd - node nodeapp.js please do reply If any idea how to fix it?
enter image description here I tried running an application of socket.io on 5000 port using node.js but it's not working.
you have to add the socket.io server to the http server, the mistake you are doing is that you are adding the socket.io server to nowhere, to the aire, try with this before to iniltialize the server on port 5000
//CREATE THE SERVER NODE JS
const server = http.createServer(app)
// CREATE SOCKET.IO SERVER CONNECT WITH OUR SERVER
const io = new Server(server);
HERE PUT YOUR SOCKET IO CODE, io.on,.....
server.listen(port,()=>{
console.log(`listening on port ${port}`)
});
const myClass = new io.(someclass)()
const socketiopackage = require('socket.io')
const port = 5000
const io = new socketiopackage.Server(5000,{cors: {"Access-Control-Allow-Origin": "*",methods: ["GET", "POST", "OPTIONS"]},})
var users = {}
io.on('connection',socket=>{
socket.on('new-user-joined',name=>{
users[socket.id]=name
socket.broadcast.emit('user-joined',name)
})
socket.on('send',message=>{
socket.broadcast.emit('recieve',{message,name:user[socket.id]})
})
})
const { Server } = require('socket.io')
const port = 5000
const io = new Server(5000,{cors: {"Access-Control-Allow-Origin": "*",methods: ["GET", "POST", "OPTIONS"]},})
var users = {}
io.on('connection',socket=>{
socket.on('new-user-joined',name=>{
users[socket.id]=name
socket.broadcast.emit('user-joined',name)
})
socket.on('send',message=>{
socket.broadcast.emit('recieve',{message,name:user[socket.id]})
})
})
Using Nodemon
npm install -g nodemon
nodemon (fileName).js
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.