NodeJS Express Socket.io在单独的文件中实现

时间:2016-08-01 13:21:26

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

我正在使用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

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

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

app.js -

io

./ websocket / server.js -

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

一切正常:)。

答案 1 :(得分:-1)

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

  

Socket.IO由两部分组成

     
      
  • 与Node.JS HTTP Server集成(或安装)的服务器: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!
});