【问题标题】:socket.io can't handle errorssocket.io 无法处理错误
【发布时间】:2016-09-02 22:54:32
【问题描述】:

我正在尝试使用 node.js 和 socket.io 制作实时应用程序。正如我所看到的,服务器可以看到新用户何时连接但无法将信息返回到客户端或其他东西。这是我在客户端的:

<script src="<?= base_url('assets/js/socket.io.js') ?>"></script>
<script>
    var socket;
    socket = io('http://***.***.***.***:3030', {query: "key=key"});

    socket.on('connect', function (data) {
        console.log('Client side successfully connected with APP.');
    });

    socket.on('error', function (err) {
        console.log('Error: ' + err);
    });
</script>

这是服务器端:

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

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

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

    if ('www.****.com' == domain) {
        globals.debug('New user connected', 'warning');
    } else {
        globals.debug('Bad site authentication data, chat will be disabled.', 'danger');
        return accept('Bad site authentication data, chat will be disabled.', false);
    }
});

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

    console.log('The user ' + sock.id + ' has connected');
    next(null, true);
});

当有人访问网站时,我希望在控制台输出中看到“新用户已连接”,我看到了:screen shot,用户应该在浏览器控制台输出中看到:“客户端与 APP 成功连接。 "但我没有显示。我也尝试向用户发送数据,但它也不起作用。我看不到任何错误或其他东西。这不是我第一次使用套接字,而是第一次面临这样的问题。也许有任何错误报告方法来处理错误或什么?我也看不到io.use(....) 方法的输出

【问题讨论】:

  • 您可以尝试删除身份验证层吗?您会看到身份验证被击中,但不是“用户 __ 已连接”。关于触发“连接”事件客户端的原因有很多文档,它可能需要先通过身份验证。
  • 是的,可以,但是如何保持身份验证呢?
  • 哦,我的错,我需要在确认一切正常后添加accept(null, true)

标签: ios node.js sockets


【解决方案1】:

解决方法是在认证后通过“OK”标志进行下一个方法:

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

if ('www.****.com' == domain) {
    globals.debug('New user connected', 'warning');
    accept(null, true);
} else {
    globals.debug('Bad site authentication data, chat will be disabled.', 'danger');
    return accept('Bad site authentication data, chat will be disabled.', false);
}

});

【讨论】:

    猜你喜欢
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 2016-09-16
    • 2013-04-16
    • 1970-01-01
    相关资源
    最近更新 更多