首页 文章

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

提问于
浏览
75

所以这是交易:我'm trying to use socket.io in an express project. After Express Js 4 was lauched, i'已更新我的快速生成器,现在应用程序初始函数进入 ./bin/www 文件,包括那些变量(www文件内容:http://jsfiddle.net/avMa5/

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

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

话虽如此,让我们记住socket.io docs如何要求我们解雇它:

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

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

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

好的,这可行,但我可以't use the io var anywhere else, and i really don' t想要将我的socket.io函数放在 www 文件上 .

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

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

8 回答

  • 9

    A tutorial for beginners from 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.
    /*  
    ...
    

    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;
    

    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>
    

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

  • 5

    事实证明它确实是一些基本的sintax问题....我从this socket.io chat tutorial获得了这些线...

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

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

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

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

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

    <3

  • 147

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

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

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

    app.io = require('socket.io')();
    

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

    app.io.attach(server);
    

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

    app = require("../app");
    

    它真的很简单

    require('socket.io')().attach(server);
    

    但这样做"difficult"方式确保 app.io 现在拥有socke.io对象 .

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

    首先在“app.js”中,做

    app.use('/', require('./routes/index')(app.io));
    

    然后在“routes / index.js”中

    module.exports = function(io){
        //now you can use io.emit() in this file
    
        var router = express.Router();
    
    
    
        return router;
     }
    

    所以“io”被注入“index.js” .

  • 36

    更新Gabriel Hautclocq的回复:

    在www文件中,由于使用Socket.io进行更新,代码应显示为以下内容 . Attach is now Listen.

    /**
     * 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);`
    

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

    /node_modules/socket.io-client/socket.io.js.
    

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

    var socket = io.connect('http://localhost:3000');
    
  • 19

    我有一个解决方案,可以在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;
    

    bin/www:

    (...)
    
    /**
     * Create HTTP server.
     */
    
    var server = http.createServer( app );
    
    
    /**
     * Socket.io
     */
    
    var io     = app.io
    io.attach( server );
    
    (...)
    

    这样,您可以访问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;
    }
    

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

    app.js

    // Socket.io
    var io = socket_io();
    app.io = io;
    
    var routes = require('./routes/index')(io);
    
  • 5

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

    bin/www

    /**
     * Socket.io
     */
    var socketApi = require('../socketApi');
    var io = socketApi.io;
    io.attach(server);
    

    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;
    

    app.js

    // Nothing here
    

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

  • 2

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

    我遇到的问题:

    • var sockIO = require('socket.io')应为var sockIO = require('socket.io') () . (信用:Zhe Hu

    • sockIO.attach应该是sockIO . listen (信用:rickrizzo

    Steps

    • 使用以下命令安装Socket.io:
    npm install --save socket.io
    
    • 将以下内容添加到 app.js
    var sockIO = require('socket.io')();
    app.sockIO = sockIO;
    
    • bin/www 中,在var server = http.createServer(app)之后,添加以下内容:
    var sockIO = app.sockIO;
    sockIO.listen(server);
    
    • 要测试功能,在 app.js 中,您可以添加以下行:
    sockIO.on('connection', function(socket){
        console.log('A client connection occurred!');
    });
    
  • 30

    以前的一些答案不起作用,而其他答案则过于复杂 . 请尝试以下解决方案......

    安装服务器端和客户端socket.io节点模块:

    npm install --save socket.io socket.io-client
    

    服务器端

    在服务器定义 var server = http.createServer(app); 之后,将以下代码添加到bin / www:

    /**
     * Socket.io
     */
    
    var io = require('socket.io')(server);
    
    io.on("connection", function(socket){
      console.log("SOCKET SERVER CONNECTION");
      socket.emit('news', { hello: 'world' });
    });
    

    客户端

    如果使用webpack,请将以下代码添加到webpack entry.js文件中:

    var socket = require('socket.io-client')();
    socket.on('connect', function(){
      console.log("SOCKET CLIENT CONNECT")
    });
    
    socket.on('news', function(data){
      console.log("SOCKET CLIENT NEWS", data)
    });
    

    完成 . 访问您的站点并查看浏览器的js开发人员控制台 .

相关问题