在 Express 4 和 express-generator 的/bin/www 中使用 socket.io [英] Using socket.io in Express 4 and express-generator's /bin/www

查看:27
本文介绍了在 Express 4 和 express-generator 的/bin/www 中使用 socket.io的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这是交易:我正在尝试在一个快速项目中使用 socket.io.Express Js 4 发布后,我更新了我的 express-generator,现在应用程序初始功能进入 ./bin/www 文件,包括那些变量(www 文件内容:http://jsfiddle.net/avMa5/ )

So here is the deal: I'm trying to use socket.io in an express project. After Express Js 4 was lauched, i've updated my express-generator and now the app initial functions goes into ./bin/www file, including those vars (www file contents: http://jsfiddle.net/avMa5/ )

var server = app.listen(app.get('port'), function() {..}

(通过 npm install -g express-generatorexpress myApp

话虽如此,让我们记住 socket.io 文档如何要求我们触发它:

that being said, let's remember how socket.io docs ask us to fire it:

var app = require('express').createServer();
var io = require('socket.io')(app);

好的,但我不能在 app.js 中这样做,就像推荐的那样.这应该在 ./bin/www 中完成才能工作.在 ./bin/www 这是我可以做的让它工作:

Ok but i can't do it inside app.js, like recommended. This should be done in ./bin/www in order to work. in ./bin/www this is what i can do to get it working:

var io = require('socket.io')(server)

好的,这可行,但我不能在其他任何地方使用 io var,而且我真的不想将 socket.io 函数放在 www 文件中.

Ok this works, but i can't use the io var anywhere else, and i really don't want to put my socket.io functions on www file.

我想这只是基本的语法,但我不能让它工作,甚至不使用 module.exports = serverserver.exports = server 也不module.exports.io = app(io) 在 www 文件

I guess this is just basic syntax, but I can't get this to work, not even using module.exports = server or server.exports = server nor module.exports.io = app(io) on www file

所以问题是:我如何使用 socket.io 将此/bin/www 文件作为我的应用程序的起点?

So the question is: how can i use socket.io having this /bin/www file as starting point of my app?

推荐答案

事实证明这确实是一些基本的语法问题......我从 这个socket.io聊天教程...

It turns out it really was some basic sintax problem.... I got these lines from this socket.io chat tutorial...

在 ./bin/www 上,就在 var server = app.listen(.....)

on ./bin/www, just after var server = app.listen(.....)

var io = require('socket.io').listen(server);
require('../sockets/base')(io);

所以现在我创建 ../sockets/base.js 文件并将这个小家伙放在里面:

so now I create the ../sockets/base.js file and put this little fellow inside it:

module.exports = function (io) { // io stuff here... io.on('conection..... }

是的!现在它可以工作了......所以我想我真的别无选择,只能在/bin/www 中启动 socket.io ,因为那是我的 http 服务器启动的地方.目标是现在我可以在其他文件中构建套接字功能,通过 require('fileHere')(io);

Yeah! Now it works... So i guess i really had no option other than starting socket.io inside /bin/www , because that is where my http server was started. The goal is that now i can build socket functionality in other file(s), keeping the thing modular, by require('fileHere')(io);

<3

这篇关于在 Express 4 和 express-generator 的/bin/www 中使用 socket.io的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆