Pav*_*ndu 2 node.js express socket.io
在我的 Express 应用程序中,使用 生成express-generator,我想在其他一些控制器文件中使用 来将数据发送到客户端套接字io。socket.io我的方法如下,但我收到以下错误。如果有人能在这种情况下帮助我,那将是一个很大的帮助。
(节点:11376)UnhandledPromiseRejectionWarning:TypeError:io.emit 不是 F:\backend\controllers\LessonController.js:169:9 处的函数
在由 生成的 Express 应用程序中express-generator,创建服务器的过程发生在/bin/www.js. 我尝试从那里导入io实例并在其他文件中使用它,但它不起作用。
bin/www.js
#!/usr/bin/env node
var app = require('../app');
var debug = require('debug')('backend:server');
var http = require('http');
var port = normalizePort(process.env.PORT || '8080');
app.set('port', port);
var server = http.createServer(app);
const io = require('socket.io')(server);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
// several other functions are omitted for brevity
module.exports = io;
Run Code Online (Sandbox Code Playgroud)
LessonController.js
const Lesson = require('../models/Lesson');
const Course = require('../models/Course');
const User = require('../models/User');
const io = require('../bin/www')
var _ = require('lodash');
module.exports = {
addComment: async (lessonId, userId, content, callback) => {
const newData = {
comments: {
user: userId,
content: content,
},
};
Lesson.findOneAndUpdate({ _id: lessonId }, { $push: newData }, {new: true})
.exec()
.then(
function (data) {
if (data) {
io.emit("comment_"+lessonId,data)
callback(null, data);
} else if (err) {
callback(err, null);
}
}
)
}
};
Run Code Online (Sandbox Code Playgroud)
这是一个解决方案
创建一个模块io.js
const sio = require('socket.io');
let io = null;
module.exports = {
//Initialize the socket server
initialize: function(httpServer) {
io = sio(httpServer);
io.on('connection', function(socket) {
console.log('New client connected with id = ', socket.id);
socket.on('disconnect', function(reason) {
console.log('A client disconnected with id = ', socket.id, " reason ==> ", reason);
});
});
},
//return the io instance
getInstance: function() {
return io;
}
}
Run Code Online (Sandbox Code Playgroud)
在bin/www.js中
var server = http.createServer(app);
require('path_to_io_js/io').initialize(server);
Run Code Online (Sandbox Code Playgroud)
在你的控制器/LessonController.js 中
//require the io module
const socket = require('path_to_io_js/io');
module.exports = {
addComment: async (lessonId, userId, content, callback) => {
const newData = { comments: { user: userId, content: content, }, };
Lesson.findOneAndUpdate({ _id: lessonId }, { $push: newData }, { new: true })
.exec().then(function (data) {
if (data) {
//get the io instance
const io = socket.getInstance();
io.emit("comment_" + lessonId, data)
}
callback(null, data);
}).catch(err => {
callback(err);
})
}
};
Run Code Online (Sandbox Code Playgroud)
您可以尝试将socket.io实例导出到全局级别并根据需要进行访问。
我的项目也是使用express-generator创建的,因此遵循相同的模板。
在我的项目中,我想统计主页中当前的活跃用户数。
这是一个例子:
bin/www
#!/usr/bin/env node
const app = require('../app');
const http = require('http').Server(app);
const io = require('socket.io')(http)
http.listen(process.env.PORT);
io.on('connection', (socket) => {
const qtd = socket.client.conn.server.clientsCount;
io.emit('novaconexao', qtd);
socket.on('disconnect', () => {
io.emit('disconnecteduser', qtd - 1);
});
});
app.set('socketio', io);//here you export my socket.io to a global
console.log('Microsservice login listening at http://localhost:%s', process.env.PORT);
Run Code Online (Sandbox Code Playgroud)
服务器/index.js
const router = require('express').Router();
router.get('/', (req, res) => {
const io = req.app.get('socketio'); //Here you use the exported socketio module
console.log(io.client.conn.server.clientsCount)
io.emit('new-user', {qtd: io.client.conn.server.clientsCount})
res.status(200).json({ msg: 'server up and running' });
})
module.exports = router;
Run Code Online (Sandbox Code Playgroud)
遵循此策略,您可以socketio在应用程序中的任何路线中使用。
| 归档时间: |
|
| 查看次数: |
2773 次 |
| 最近记录: |