【问题标题】:NodeJS Express Socket.io Impletation in a Seperate File单独文件中的 NodeJS Express Socket.io 实现
【发布时间】:2016-08-01 13:21:25
【问题描述】:

我正在使用Node.JS Express v4socket.io 来实现WebSocket。

我的app.js是这样的-

var express = require('express');
var socket_io = require( "socket.io" );
var path = require('path');
var favicon = require('serve-favicon');
//var controllers = require('./controllers');
//var middleware = require('./middleware');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

// Express
var app          = express();

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

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.set('view options', { layout: false });     //Disabling default layout
require('./view_partials')(app);

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

require('./routes')(app);

//// Socket.io server listens to our app

    //Server - Data received
        // Send current time to all connected clients
        function sendTime()
        {
            io.emit('time', { time: new Date().toJSON() });
        }

        // Send current time every 10 secs
        setInterval(sendTime, 10000);

    //Client - Data received
        // Emit welcome message on connection
        io.on('connection', function(socket)
        {
            // Use socket to communicate with this particular client only, sending it it's own id
            socket.emit('welcome', { message: 'Welcome!', id: socket.id });
            socket.on('i am client', console.log);
        });
////////////////////////////////////////

require('./errors')(app);

module.exports = app;

我喜欢导出这段代码-

    //Client - Data received
        // Emit welcome message on connection
        io.on('connection', function(socket)
        {
            // Use socket to communicate with this particular client only, sending it it's own id
            socket.emit('welcome', { message: 'Welcome!', id: socket.id });
            socket.on('i am client', console.log);
        });

到一个新文件。

那么,我所做的就是这样-

client.js-

//Client - Data received
    // Emit welcome message on connection
    io.on('connection', function(socket)
    {
        // Use socket to communicate with this particular client only, sending it it's own id
        socket.emit('welcome', { message: 'Welcome!', id: socket.id });
        socket.on('i am client', console.log);
    });

app.js-

var express = require('express');
var socket_io = require( "socket.io" );
var path = require('path');
var favicon = require('serve-favicon');
//var controllers = require('./controllers');
//var middleware = require('./middleware');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

// Express
var app          = express();

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

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.set('view options', { layout: false });     //Disabling default layout
require('./view_partials')(app);

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

require('./routes')(app);

//// Socket.io server listens to our app

    //Server - Data received
        // Send current time to all connected clients
        function sendTime()
        {
            io.emit('time', { time: new Date().toJSON() });
        }

        // Send current time every 10 secs
        setInterval(sendTime, 10000);

    require('./websocket/client');
////////////////////////////////////////

require('./errors')(app);

module.exports = app;

但是既不给我错误也不工作。

谁能帮忙,我怎样才能将它导出到一个单独的文件中,以便可以分离客户端和服务器代码?

我的完整代码可以在here找到。

提前感谢您的帮助。

【问题讨论】:

    标签: node.js express websocket socket.io maintainability


    【解决方案1】:

    我已经解决了这个问题。我们需要共享io 变量来包含文件。

    app.js -

    require('./websocket/server')(io);
    

    还有 ./websocket/server.js -

    // Socket.io server listens to our app
    module.exports = function(io)
    {
        // Send current time to all connected clients
        function sendTime()
        {
            io.emit('time', { time: new Date().toJSON() });
        }
        // Send current time every 10 secs
        setInterval(sendTime, 10000);
    }
    

    一切正常:)。

    【讨论】:

      【解决方案2】:

      来自http://socket.io/get-started/chat/

      Socket.IO由两部分组成

      • 与 Node.JS HTTP 服务器集成(或安装在其上)的服务器:socket.io
      • 在浏览器端加载的客户端库:socket.io-client

      您为服务器和客户端上的套接字编写处理程序/发射器。客户端处理程序/发射器必须包含在客户端 javascript 中,以便客户端浏览器能够访问它们。客户端 javascript 始终位于与服务器端代码不同的文件中。

      您可以查看上面链接的 Socket.IO 入门教程以获取更多信息。

      作为一个简单的示例,您可以在服务器代码中添加以下内容(您的 app.js)。此代码侦听新的客户端连接,然后向连接的客户端发出welcome 事件。

      var io = require('socket.io')(http)
      
      // Listen for socket events
      io.on('connection', function(socket) {
          // a client has connected!
          // emit a message to it
          var msg = "Hello client!"
          socket.emit('welcome', msg);
      });
      

      下面是客户端 (client.js) 上会发生的事情:

      var socket = io();
      
      // add event listeners to the socket
      // on 'welcome' event, log the response to console
      socket.on('welcome', function(msg) {
          console.log(msg);
          // Hello client!
      });
      

      【讨论】:

      • 您好,您所说的是一个普遍的概念,大家都知道。如果您想提供帮助,请回答我的具体问题。谢谢
      • 对不起,我一定没有完全理解你的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-16
      • 2012-11-07
      • 2014-07-02
      相关资源
      最近更新 更多