使用Express 4中的socket.io和express-generator的/ bin/www

use*_*978 84 javascript node.js express socket.io

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

var server = app.listen(app.get('port'), function() {..}
Run Code Online (Sandbox Code Playgroud)

(npm install -g express-generator然后检查它express myApp

那就是说,让我们记住socket.io docs如何要求我们解雇它:

var app = require('express').createServer();
var io = require('socket.io')(app);
Run Code Online (Sandbox Code Playgroud)

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

var io = require('socket.io')(server)
Run Code Online (Sandbox Code Playgroud)

好的,这是有效的,但我不能在其他任何地方使用io var,我真的不想把我的socket.io函数放在www文件上.

我想这仅仅是基本的语法,但我不能得到这个工作,即使不使用module.exports = server或者server.exports = server也不module.exports.io = app(io)在WWW文件

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

Gab*_*ocq 156

我有一个解决方案,可以在app.js中使用socket.io.

app.js:

var express      = require( "express"   );
var socket_io    = require( "socket.io" );

// Express
var app          = express();

// Socket.io
var io           = socket_io();
app.io           = io;

(...)

// socket.io events
io.on( "connection", function( socket )
{
    console.log( "A user connected" );
});

module.exports = app;

// Or a shorter version of previous lines:
//
//    var app = require( "express"   )();
//    var io  = app.io = require( "socket.io" )();
//    io.on( "connection", function( socket ) {
//        console.log( "A user connected" );
//    });
//    module.exports = app;
Run Code Online (Sandbox Code Playgroud)

斌/ WWW:

(...)

/**
 * Create HTTP server.
 */

var server = http.createServer( app );


/**
 * Socket.io
 */

var io     = app.io
io.attach( server );

(...)
Run Code Online (Sandbox Code Playgroud)

这样,您可以访问app.js中的io变量,甚至可以通过将module.exports定义为接受io作为参数的函数使其可用于您的路径.

index.js

module.exports = function(io) {
    var app = require('express');
    var router = app.Router();

    io.on('connection', function(socket) { 
        (...) 
    });

    return router;
}
Run Code Online (Sandbox Code Playgroud)

然后,在设置后将io传递给模块:

app.js

// Socket.io
var io = socket_io();
app.io = io;

var routes = require('./routes/index')(io);
Run Code Online (Sandbox Code Playgroud)

  • "......如果你愿意,甚至可以将它提供给你的路线." 好的,但是怎么样?如果你能举一个如何做的例子会很棒. (7认同)
  • 这只是将io变量放入app对象的问题.它也可以是:app.io = socket_io(); (3认同)
  • 当您可以使用`module.exports = { app, io }` 代替时,为什么要使用`app.io = io` (3认同)
  • @GabrielHautclocq 我如何从我的路线访问它?欣赏它! (2认同)
  • 将自定义属性附加到`app`对象不是**坏**更好地使用符号或`app.set()`. (2认同)

Ana*_*oly 48

一种不同的启动方法socket.io,它将所有相关代码分组在一个地方:

斌/ WWW

/**
 * Socket.io
 */
var socketApi = require('../socketApi');
var io = socketApi.io;
io.attach(server);
Run Code Online (Sandbox Code Playgroud)

socketApi.js

var socket_io = require('socket.io');
var io = socket_io();
var socketApi = {};

socketApi.io = io;

io.on('connection', function(socket){
    console.log('A user connected');
});

socketApi.sendNotification = function() {
    io.sockets.emit('hello', {msg: 'Hello World!'});
}

module.exports = socketApi;
Run Code Online (Sandbox Code Playgroud)

app.js

// Nothing here
Run Code Online (Sandbox Code Playgroud)

通过这种方式socket.io,我可以从应用程序的任何地方调用一个模块中的所有相关代码和函数.

  • 这个答案值得更多的赞成!非常简单和干净,它将套接字路由保持在*www*,*app.js*之外,并且还在*index.js*之外(是的,在*index.js*之外),此文件应该只包含Express HTTP路由. (3认同)
  • 谁能为socket.io 2.0更新它?它对我不起作用。io.attach(server)和io.listen(server)都抛出“无法读取未定义的属性X”。 (2认同)

use*_*978 40

事实证明它确实是一些基本的sintax问题....我从这个socket.io聊天教程得到了这些行...

在./bin/www之后 var server = app.listen(.....)

var io = require('socket.io').listen(server);
require('../sockets/base')(io);
Run Code Online (Sandbox Code Playgroud)

所以现在我创建了../sockets/base.js文件并将这个小伙伴放在其中:

module.exports = function (io) { // io stuff here... io.on('conection..... }
Run Code Online (Sandbox Code Playgroud)

是啊!现在它的工作原理......所以我想我除了在/ bin/www中启动socket.io之外别无选择,因为这是我的http服务器启动的地方.目标是,现在我可以在其他文件中构建套接字功能,保持模块化,通过require('fileHere')(io);

<3

  • @Gofilord,因为它击败了套接字的整个目的......你需要的是包括渲染在内的常规路由.套接字只是在没有http请求的情况下在客户端和服务器之间发送消息.也许请阅读这篇文章http://enterprisewebbook.com/ch8_websockets.html (3认同)

Zhe*_* Hu 19

旧的"expressjs",一切都发生在"app.js"文件中.所以socket.io绑定到服务器也发生在该文件中.(顺便说一句,人们仍然可以用旧的方式去做,并删除bin/www)

现在使用新的expressjs,它需要在"bin/www"文件中发生.

幸运的是,javascript/requirejs使传递对象变得容易.正如Gabriel Hautclocq指出的那样,socket.io仍在"app.js"中"导入",它通过一个属性附加到"app"对象

app.io = require('socket.io')();
Run Code Online (Sandbox Code Playgroud)

socket.io通过在"bin/www"中附加服务器而生效.

app.io.attach(server); 
Run Code Online (Sandbox Code Playgroud)

因为"app"对象早先传递到"bin/www"

app = require("../app");
Run Code Online (Sandbox Code Playgroud)

它真的很简单

require('socket.io')().attach(server);
Run Code Online (Sandbox Code Playgroud)

但是以"困难"的方式实现它确保了app.io现在拥有socke.io对象.

现在,如果你在"routes/index.js"中也需要这个socket.io对象,那么只需使用相同的原理来传递该对象.

首先在"app.js"中,做

app.use('/', require('./routes/index')(app.io));
Run Code Online (Sandbox Code Playgroud)

然后在"routes/index.js"中

module.exports = function(io){
    //now you can use io.emit() in this file

    var router = express.Router();



    return router;
 }
Run Code Online (Sandbox Code Playgroud)

所以"io"被注入"index.js".


ric*_*zzo 9

更新Gabriel Hautclocq的回复:

在www文件中,由于使用Socket.io进行更新,代码应显示为以下内容.附件现在是听.

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);


/**
 * Socket.io
 */
var io = app.io;
io.listen(server);`
Run Code Online (Sandbox Code Playgroud)

此外,要使该连接正常工作,还需要实现客户端API.这不是Express特定的,但没有它,连接调用将不起作用.API包含在

/node_modules/socket.io-client/socket.io.js. 
Run Code Online (Sandbox Code Playgroud)

在前端包含此文件并使用以下内容进行测试:

var socket = io.connect('http://localhost:3000');
Run Code Online (Sandbox Code Playgroud)


Bri*_*ian 6

阅读完所有评论后,我使用Socket.io Server Version:1.5.0提出了以下内容

我遇到的问题:

  1. var sockIO = require('socket.io')应该是 var sockIO = require('socket.io')().(感谢:哲虎)

  2. sockIO.attach应该是sockIO.(感谢:rickrizzo)

脚步

  1. 使用以下命令安装Socket.io:

    npm install --save socket.io
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将以下内容添加到app.js:

    var sockIO = require('socket.io')();
    app.sockIO = sockIO;
    
    Run Code Online (Sandbox Code Playgroud)
  3. bin/www中,在var server = http.createServer(app)之后,添加以下内容:

    var sockIO = app.sockIO;
    sockIO.listen(server);
    
    Run Code Online (Sandbox Code Playgroud)
  4. 要测试功能,可以在app.js中添加以下行:

    sockIO.on('connection', function(socket){
        console.log('A client connection occurred!');
    });
    
    Run Code Online (Sandbox Code Playgroud)


小智 5

来自Cedric Pabst的初学者教程
是应用程序聊天链接的简短基础知识:

使用express-generate和ejs引擎,可以在express-generate中的每个.ejs文件标准路由中使用

编辑文件bin\www并添加此app.io.attach(服务器); 像这样

...
/*
 * Create HTTP server.
/*  
var server = http.createServer(app);
/*
 * attach socket.io
/*  
app.io.attach(server); 
/*
 * Listen to provided port, on all network interfaces.
/*  
...
Run Code Online (Sandbox Code Playgroud)

app.js中编辑

//connect socket.io
... var app = express();
// call socket.io to the app
app.io = require('socket.io')();

//view engine setup
app.set('views', path.join(_dirname, 'views'));
...



...
//start listen with socket.io
app.io.on('connection', function(socket){
console.log('a user connected');

// receive from client (index.ejs) with socket.on
socket.on('new message', function(msg){
      console.log('new message: ' + msg);
      // send to client (index.ejs) with app.io.emit
      // here it reacts direct after receiving a message from the client
      app.io.emit('chat message' , msg);
      });
});
...
module.exports = app;
Run Code Online (Sandbox Code Playgroud)

index.ejs中编辑

 <head>  
   <title><%= title %></title>
   <link rel='stylesheet' href='/stylesheets/style.css' />
   <script src="/socket.io/socket.io.js"></script>
   //include jquery
   <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
   <script>
   var socket = io();
   //define functions socket.emit sending to server (app.js) and socket.on receiving 
     // 'new message' is for the id of the socket and $('#new-message') is for the button
     function sendFunction() {
     socket.emit('new message', $('#new-message').val());
     $('#new-message').val('');
   }
    // 'chat message' is for the id of the socket and $('#new-area') is for the text area
   socket.on('chat message', function(msg){
     $('#messages-area').append($('<li>').text(msg));
   });
   </script>
 </head>  

 <body>  
   <h1><%= title %></h1>
   <h3>Welcome to <%= title %></h3>
   <ul id="messages-area"></ul>
   <form id="form" onsubmit="return false;">
     <input id="new-message" type="text" /><button onclick="sendFunction()">Send</button>
   </form>
 </body>
Run Code Online (Sandbox Code Playgroud)

玩得开心:)并感谢很多Cedric Pabst