为什么我的Socket.io事件多次触发?

时间:2017-06-20 19:48:38

标签: javascript socket.io form-submit

我正在使用Socket.io构建一个简单的聊天室。用户输入所需的用户名并提交表单。

我检查用户名是否正在使用,如果用户名可用,则触发join事件,这会将其添加到聊天中,但join事件似乎是针对每个用户触发的目前正在聊天 - 不只是新用户进入聊天。

客户端

var socket = io();

// user enters desired username and submits form
$('#chat__join').on('submit', function() {

    // get username value
    var name = $('#chat__name').val();

    // send socket username to check if someone is already using it
    socket.emit('isUserInChat', name);

    return false;
});

// callback for when we know if user is already in chat or not
socket.on('isUserInChat', function(exists, name) {

    if(!exists) {

        // this only fires once per form submission
        console.log('username is available');

        // but this fires per user
        socket.emit("join", name);
    } else {
        // username is taken
        // display error message
    }
});

当第一个人提交表单时,socket.emit("join", name);行似乎会触发一次,这是正确的。但是当第二个人提交表单时,join事件会被触发两次。当第三人提交表格时,它会被解雇三次。为什么每个用户都会触发事件?它不应该只针对表单提交而触发吗?

服务器

var express = require('express'),
    app = express(),
    http = require('http').Server(app),
    io = require('socket.io')(http),
    usersObj = {
        users: []
    };

io.on('connection', function(socket) {

    socket.on('isUserInChat', function(username) {

        var flag = false;

        // for each user
        for(var i = 0; i < usersObj.users.length; i++) {

            // if username matches username that was entered
            if(usersObj.users[i].username == username) {

                // set flag to be true
                flag = true;
            }
        }

        // send client true or false
        io.emit('isUserInChat', flag, username);
    });

    socket.on('join', function(name) {

        // construct user
        var user = {
            id: socket.id,
            username: name
        };

        // add user to users object array
        usersObj.users.push(user);

        // send chat message
        io.emit('sendMsg', 'Chat Bot', name+' has connected to the server.');
    });
});

1 个答案:

答案 0 :(得分:2)

你似乎很困惑,但实际上你告诉事件要向每个客户发出。如果您希望它仅回显给检查可用性的客户端

io.emit('isUserInChat', flag, username);

应该是

socket.emit('isUserInChat', flag, username);