javascript - Socket.io 类型错误 : undefined is not a function

标签 javascript node.js socket.io

我正在制作一个简单的聊天应用程序。连接“loggin in”并发送聊天消息一切顺利。但是,当我刷新页面并尝试再次登录时,出现错误;

Missing error handler on socket.
TypeError: undefined is not a function at Socket. '<'anonymous>
[ . . . ] at server.js:30:19

服务器.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var path = require('path');

var users = [];
var chat_history = [];

[...]

io.on('connection', function(socket){
    //
    // LOGIN
    ///////////////////////////
    socket.on('login', function(username) {
        if(!socket.username && username) {
            socket.emit('logged_in', 'successful');
            socket.emit('chat_history', JSON.stringify(chat_history));
            io.emit('notice', username + ' has connected.');
            socket.username = username;
            users.push(username);

            update_users();


            //
            // CHAT MESSAGE RECEIVED
            ///////////////////////////
            socket.on('chat_message', function(msg){
                var message = getTime() + ' ' + socket.username + ': ' + msg;

                update_chat_history(message);
            });


            //
            // DISCONNECT
            ///////////////////////////
            socket.on('disconnect', function () {
                io.emit('notice', socket.username + ' has left the channel.');
                console.log(socket.username + ' disconnected');

                update_users();
            });
        } else {
            socket.emit('logged_in', 'unsuccessful');
            socket.emit('notice', 'Login was unsuccessful, please refresh the page and try again.');
        }
    });


    ///////////////////////////////////////////
    //socket.on('error', function (err){
    //    console.error(err.stack);
    //});
    ///////////////////////////////////////////
});

http.listen(port, ip);

console.log('listening on ' + ip + ':' + port);



//
// Functions
///////////////////////////
function getTime() {
    var t = new Date();
    t = '[' + t.getUTCHours() + ' : ' + t.getUTCMinutes() + ']';

    return t;
}

function update_users() {
    //console.log(io.sockets.connected);
    users = [];

    for( var client in io.sockets.connected ){
        var username = io.sockets.connected[client].username;
        if(username){
            users.push(username);
        }
    }

    users = JSON.stringify(users);
    io.emit('users_online', users);
}

function update_chat_history(message_to_add){
    chat_history.push(message_to_add);

    if(chat_history.length > 20){
        chat_history.splice(0, 1);
    }
}

在socket.on('login')处,我测试了刷新页面或断开连接后套接字不会未定义。
我想这与不更新连接并尝试重新连接到相同的连接有关,但我不知道如何或是什么。在 stackoverflow 上找不到解决方案。感谢帮助。

UPDATE: Blaargh this just doesnt make any at all (╯°□°)╯︵ ┻━┻

Still the same error. now at server.js:78:11

http://1.1m.yt/kgaZSBfUa.png

Removed all socket.usernames and changed login to;

socket.on('login', function(username) {
    if( username ) { // TODO what if duplicate username
        socket.emit('logged_in', 'successful');
        socket.emit('chat_history', JSON.stringify(chat_history));
        io.emit('notice', username + ' has connected.');

        add_user(socket.id, username);
        [...]

Also changed the update_users()

function add_user(id, username){
    users.push({
        'id' : id,
        'username' : username
    });

    var json_users = JSON.stringify(users);
    io.emit('users_online', json_users);
}

function remove_user(id){
    for(user in users){
        if(users[user]['id'] == id){
            users.splice(users[user], 1);
            break;
        }
    }
    var json_users = JSON.stringify(users);
    io.emit('users_online', json_users);
}


UPDATE: 2

I still have no clue at all what could have been the problem however somehow I managed to write around it so its working now.

最佳答案

每次刷新页面时,您的套接字都会被删除并创建一个新的套接字(没有属性用户名,因为它是一个新套接字),因此您需要找到一种方法来保留您的用户名

对于您的情况,我建议您将用户名放入 cookie 中,并检查页面加载是否 cookie“用户名”存在并且有值(value)(如果存在),然后更新您的(新)套接字

更高级的方法: handle browser reload socket io

希望这有帮助!

编辑

npm install --save lodash

    var _ = require('lodash')
    var users = [];

    io.sockets.on('connection', function (socket) {
        socket.username ="guest"
     socket.on('login', function(username) {
            if( username) {
                socket.emit('logged_in', 'successful');
                io.emit('notice', username + ' has connected.');
                socket.username = username ;
                // users.push(username);
            add_user(socket.id, username , users);

                //
                // CHAT MESSAGE RECEIVED
                ///////////////////////////
                socket.on('chat_message', function(msg){
                    var message = date.Now() + ' ' + socket.username + ': ' + msg;

                });


                //
                // DISCONNECT
                ///////////////////////////
                socket.on('disconnect', function () {
                    io.emit('notice', socket.username + ' has left the channel.');
                    console.log(socket.username + ' disconnected');


                });
            } else {
                socket.emit('logged_in', 'unsuccessful');
                socket.emit('notice', 'Login was unsuccessful, please refresh the page and try again.');
            }
        });



        socket.emit('message', { message: 'welcome to the chat' });
        socket.on('send', function (data) {
            io.sockets.emit('message', data);
        });
    });
    console.log("Listening on port " + port);


    function add_user(id, username , users){

        var item = {
            'id' : id,
            'username' : username
        }

     var oldItem = _.find(users, {id: id});
              var index = users.indexOf(oldItem);

              if (oldItem) {
                users.splice(index, 1);
                users.unshift(item);
              } else {
                users.unshift(item);
              }





        users = JSON.stringify(users);
            console.log(users)
        io.emit('users_online', users);
    }

    function remove_user(id){
        for(user in users){
            if(users[user]['id'] == id){
                users.splice(users[user], 1);
                break;
            }
        }
        users = JSON.stringify(users);
        io.emit('users_online', users);
    }

关于javascript - Socket.io 类型错误 : undefined is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33159026/

相关文章:

javascript - 在 Firefox 上按下空格键时禁用向下滚动

javascript - 类与 jquery 比较

node.js - ionic+firebase+elasticsearch 无法使用 elasticsearch.js 进行身份验证

node.js - PassportJS身份验证和mongodb数据库收集最佳实践?

node.js - socket.io 发送给一个不工作的客户端

javascript - AngularJS 设置多选下拉列表的值

javascript - React-places-autocomplete 按下下面的其他组件

javascript - Node.js 文档字数统计输出在元素 id 中

javascript - Nodejs - Express - 我无法连接到 Socket IO 对象可能是什么问题?

javascript - Angular ,Socket.io : Emit an array of object