如何在最新的mean.io中使用socket.io? [英] How to use socket.io with the latest mean.io?
问题描述
我已经获取了最新版Mean.io的副本,并注意到与以前使用的以前版本相比,存在许多更改.现在,我正在做的是创建一个非常基本的聊天应用程序,该应用程序将 socket.io 与房间一起使用.按照Socket文档中的基本设置,我必须实现以下内容:
I have fetched a copy of the latest Mean.io and noted quite a number of changes compared to the previous version I have been working with before. Now, what I am doing is creating a very basic chat application that uses socket.io with rooms. Following the basic setup in the Socket documentation I have to implement the following:
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
我在哪里定义基本的插座间设置?
Where would I define the basic socket room setup?
socket.set("log level", 1);
var people = {};
var rooms = {};
var clients = [];
推荐答案
您可以将socket.io设置为在服务器上监听
You can set the socket.io to listen on your server on
/server/config/system/bootstrap.js
需要socket.io模块
Require the socket.io module
var express = require('express'),
appPath = process.cwd(),
io = require('socket.io');
现在将socket.io设置为监听您的应用
Now set the socket.io to listen on your app
// Express settings
var app = express();
require(appPath + '/server/config/express')(app, passport, db);
io = io(app.listen(3000));
return io;
然后,您需要在bootstrapDependencies()函数上将socket.io对象注入到您的应用中.
Then you need to inject the socket.io object into your app on bootstrapDependencies() function.
function bootstrapDependencies() {
...
// Register socket.io dependency
mean.register('io', function() {
return io;
});
}
均值.使用此项目进行依赖项注入 https://www.npmjs.org/package/dependable
Mean.uses this project for its dependency injection https://www.npmjs.org/package/dependable
最后,您需要配置您的应用程序以侦听每个套接字连接 可能您想在主应用程序的路由器上进行以下操作
Finally you need to configure your app to listen on every socket connections probably you want to do these on your main app's router at
/server/routes/index.js
示例连接处理程序
var io = require('meanio').io;
io.on('connection', function (socket) {
// emit data to the clients
socket.emit('news', { hello: 'world' });
// event listeners
socket.on('my other event', function (data) {
// call your controller function here
Controller.action(data);
});
});
更重要的是,不要忘记在客户端设置socket.io.
And more importantly, don't forget to setup socket.io on the client side.
// on '/server/views/includes/foot.html'
<script src='/socket.io/socket.io.js'></script>
<script>
var socket = io();
</script>
这篇关于如何在最新的mean.io中使用socket.io?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!