【问题标题】:Socket.io connect event never firedSocket.io 连接事件从未触发
【发布时间】:2015-06-04 17:22:48
【问题描述】:

我正在使用 nodejs 和 socket.io 创建一个套接字服务器。问题是,在客户端和服务器上,连接事件永远不会被触发。我的客户代码是这样的:

var socket = io.connect("http://127.0.0.1:8002");

console.log(socket); // This works

socket.on('connect', function(){
   console.log('connected');  // Does not show meaning event not fired
});

然后,在服务器上,这就是我得到的:

var http = require('http');
var server = http.createServer().listen(8002);
var io = require('socket.io').listen(server);
var cookie_reader = require('cookie');
var querystring = require('querystring');
var redis = require('redis');

//Configure socket.io to store cookie set by Django
io.use(function(){
    io.set('authorization', function(data, accept){
        if(data.headers.cookie){
            data.cookie = cookie_reader.parse(data.headers.cookie);
            return accept(null, true);
        }
        return accept('error', false);
    });
    // io.set('log level', 1);
    // io.set('origins', 'http://127.0.0.1:8001');
});

io.sockets.on('connection', function (socket) {
    console.log("Someone connected"); // Nothing shows
    // Create redis client
    /*client = redis.createClient();

    // Subscribe to the Redis events channel
    client.subscribe('notifications.' + socket.handshake.cookie['sessionid']);

    // Grab message from Redis and send to client
    client.on('message', function(channel, message){
        console.log('on message', message);
        socket.send(message);
    });

    // Unsubscribe after a disconnect event
    socket.on('disconnect', function () {
        client.unsubscribe('notifications.' + socket.handshake.cookie['sessionid']);
    });*/
});

如果有帮助,我正在使用this tutorial。我做错了什么?

【问题讨论】:

    标签: node.js sockets websocket socket.io


    【解决方案1】:

    除非你需要 redis / django 和所有其他花哨的东西,

    我建议只使用 socket.io 网站上的入门文档:

    http://socket.io/docs/

    【讨论】:

    • 我真的需要这些,但我已经能够将问题缩小到 io.use() 部分的 nodejs 代码,即配置 socket.io 以存储 Django 设置的 cookie
    猜你喜欢
    • 2020-09-25
    • 2017-01-18
    • 2016-07-14
    • 2014-04-03
    • 2016-03-28
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    相关资源
    最近更新 更多