Nodejs套接字发射不起作用

时间:2016-09-15 18:59:44

标签: node.js sockets

我的nodejs应用程序既不适用于套接字服务器。它与用户端连接,但我无法处理任何事件。

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

http.listen(appSettings.RUNNING_PORT, function () {
    globals.debug('Server is running on port: ' + appSettings.RUNNING_PORT, 'success');
});

io.set('authorization', function (handshakeData, accept) {
    if (handshakeData && handshakeData.headers && handshakeData.headers.referer) {
        var domain = handshakeData.headers.referer.replace('http://', '').replace('https://', '').split(/[/?#]/)[0];

        if ('**' == domain) {
            accept(null, true);
        } else {
            globals.debug('Bad site authentication data, game will be disabled.', 'danger');
            return accept('Bad site authentication data, game will be disabled.', false);
        }
    } else {
        accept('Failed transaction', false);
    }


    io.use(function (sock, next) {
        var handshakeData = sock.request;
        var userToken = handshakeData._query.key;

        users.prepare(io, []);
        users.defineUser(userToken, sock.id, next);

        // start the game
        game.prepare(io, []);
        game.startPolling();
    });
});

所以我在这里连接并要求一些方法。 users.defineUser(userToken, sock.id, next);

this.defineUser = function (token, sockID, next) {
    if (token) {
        Promise.try(function () {
            return db('users')
                .where('key', '=', token)
                .orderBy('id', 'desc')
                .limit(1);
        }).then(function (result) {
            if (result && result.length > 0) {
                self.io.to(sockID).emit('connect-success', {
                    message: 'Successfully connected',
                    data: {
                        name: result[0].name
                    }
                });

                globals.debug('User '+ result[0].name +' connected as ' + sockID, 'success');
                next('Successfully connected', true);
            } else {
                self.io.to(sockID).emit('global-error', {
                    message: 'Only connected users are available to play'
                });

                next(false, false);
            }
        }).catch(function (e) {
            if (e.code) {
                self.io.to(sockID).emit('global-error', {
                    message: 'There was a problem with our database, please try later. ' + e.code
                });

                next(false, false);
            }
        });
    } else {
        self.io.to(sockID).emit('global-error', {
            message: 'Only connected users are available to play'
        });

        next(false, false);
    }
};

所以我可以看到调试"用户Sandra连接为/#Q82F5WCvLZvgy65YAAAB"但是当我尝试向用户发送任何内容时,它不起作用。

即使在前端,我也可以通过调用socket.on('connection)方法看到应用与用户建立了联系。那么问题出在哪里呢?

0 个答案:

没有答案