在Node中封装Socket.io事件?

时间:2015-11-09 18:12:17

标签: javascript node.js socket.io

我希望将我的Socket.io events / init与我的主节点服务器逻辑分开。目标是不仅维护Socket.io代码,还维护我可能发出的任何事件。

我对理解这个范围以及使用Node进行封装的方法有点不知所措,并且希望能够对更好的做事方式做一些澄清。

server.js

//-- Socket.io
var http = require('http').Server(app);

//-- Encapsulate Socket init/events
var io = require('./socket.js').listen(http)

var api = express.Router();

api.route('/users/:user_id')
    .put(function(req, res) {
        io.dispatch(req.body.event);
    }
}

//-- Start Server
http.listen(port);
console.log('Server started on port: ' + port);

io.init(app);

socket.js

'use strict'

var io = require('socket.io');
var ioJwt = require('socketio-jwt');

var clientsConnected = 0;
var ioServer;

exports.listen = function(http, app) {
    ioServer = io.listen(http);
    return ioServer;
}

exports.init = function(app) {

    ioServer.use(ioJwt.authorize({
        secret: app.get('secret'),
        handshake: true
    }));

        ioServer.on('connection', function(socket){
        connect();

        socket.on('error', function(err) {
            console.log('Socket.IO error:');
            console.log(err);
        });

        socket.on('disconnect', function(){
            disconnect();
        });
    });
}

function connect() {
    clientsConnected++;

    console.log('user connected. ' + clientsConnected + ' total.');
}

function disconnect() {
    clientsConnected--;

    console.log('user disconnected. ' + clientsConnected + ' total.');
}

1 个答案:

答案 0 :(得分:0)

两个模块需要的最小通信是必须将http服务器提供给套接字模块,以便它可以正确初始化,并且http服务器必须调用套接字模块以适当地分派。因此,您可以进行仅具有这两种连接的模块化:

<强> server.js

'use strict'

var io = require('socket.io');
var ioJwt = require('socketio-jwt');

var clientsConnected = 0;
var ioServer;

module.exports = function(server) {
    ioServer = io.listen(server);
    ioServer.use(ioJwt.authorize({
        secret: app.get('secret'),
        handshake: true
    }));

    ioServer.on('connection', function(socket){
    connect();

    socket.on('error', function(err) {
        console.log('Socket.IO error:');
        console.log(err);
    });

    socket.on('disconnect', function(){
        disconnect();
    });

    // return dispatch function
    return function(data) {
        io.dispatch(data);
    }
}

function connect() {
    clientsConnected++;

    console.log('user connected. ' + clientsConnected + ' total.');
}

function disconnect() {
    clientsConnected--;

    console.log('user disconnected. ' + clientsConnected + ' total.');
}

<强> sockets.js

my-project.jar/spring/config.xml