初始提交
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
let io = null;
|
||||
|
||||
module.exports = {
|
||||
init: (httpServer) => {
|
||||
io = require('socket.io')(httpServer, {
|
||||
cors: {
|
||||
origin: "*",
|
||||
methods: ["GET", "POST"]
|
||||
}
|
||||
});
|
||||
|
||||
io.engine.on('connection_error', (err) => {
|
||||
try {
|
||||
const ctx = err && err.context ? err.context : null;
|
||||
const req = ctx && ctx.req ? ctx.req : null;
|
||||
const headers = req && req.headers ? req.headers : {};
|
||||
console.log('Socket connection error:', {
|
||||
code: err && err.code,
|
||||
message: err && err.message,
|
||||
url: req && req.url,
|
||||
transport: ctx && ctx.transport,
|
||||
host: headers && headers.host,
|
||||
origin: headers && headers.origin
|
||||
});
|
||||
} catch (e) {
|
||||
console.log('Socket connection error');
|
||||
}
|
||||
});
|
||||
|
||||
io.on('connection', (socket) => {
|
||||
console.log('Client connected:', socket.id);
|
||||
socket.on('disconnect', () => {
|
||||
console.log('Client disconnected:', socket.id);
|
||||
});
|
||||
});
|
||||
|
||||
return io;
|
||||
},
|
||||
getIO: () => {
|
||||
if (!io) {
|
||||
throw new Error("Socket.io not initialized!");
|
||||
}
|
||||
return io;
|
||||
},
|
||||
emit: (event, data) => {
|
||||
if (io) {
|
||||
io.emit(event, data);
|
||||
}
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user