How to export and emit even for socket io from different scripts ?
CodePudding user response:
- By this method it is only convenient to emit an event
- You can initialize a class like this
- ServerMainFile
const { Server }= require('socket.io')
class socketioserver{
constructor(){
this.io=new Server(3000,{cors: {"Access-Control-Allow-Origin": "*",methods: ["GET", "POST", "OPTIONS"]},});
this.io.on('connection',socket=>{
console.log(socket.id)
})
}
emit(eventName,data,id){
if(id) return this.io.to(id).emit(eventName,data)
this.io.emit(eventName,data)
}
on(eventName){
return new Promise((resolve,reject)=>{
this.io.on('connection',(socket)=>{
socket.on(eventName,(data)=>{
resolve(data)
})
})
})
}
io
}
const ioServer=new socketioserver()
ioServer.emit('apple','