node.js - 套接字事件之间的区别

标签 node.js sockets socket.io

有什么区别:

io.sockets.socket();
io.sockets.emit();
io.sockets.on();

sockets.on();
socket.broadcast.emit();
socket.emit();

谁能解释一下它们之间有什么区别吗?我知道sockets.on();是一个事件监听器,但我不知道区别。

而且...我怎样才能将这两行合并为一行?

socket.on('msg_user', function(usr, username, msg) {
    io.sockets.socket(usernames[usr]).emit('msg_user_handle', username, msg);
    io.sockets.socket(usernames[username]).emit('msg_user_handle', username, msg);
});

我可以使用 io.sockets.emit();但我不想在所有连接的套接字中发出,只在消息发送者和接收者上发出。

这是我的整个应用程序:

app.js

var app = require('express')(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server);

server.listen(8008);

// usernames which are currently connected to the chat
//var usernames = {};
var usernames = new Object();

function check_key(v) {
    var val = '';

    for(var key in usernames) {
        if(usernames[key] == v)
        val = key;
    }
    return val;
}

io.sockets.on('connection', function (socket) {
    // when the client emits 'adduser', this listens and executes
    socket.on('adduser', function(username){
        // we store the username in the socket session for this client
        socket.username = username;
        // add the client's username to the global list
        usernames[username] = socket.id;
        // echo to client they've connected
        socket.emit('updatechat', 'server', 'you have connected');
        // echo globally (all clients) that a person has connected
        socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected: ' + socket.id);
        // update the list of users in chat, client-side
        io.sockets.emit('updateusers', usernames);
    });

    // when the user disconnects.. perform this
    socket.on('disconnect', function(){
        // remove the username from global usernames list
        delete usernames[socket.username];
        // update list of users in chat, client-side
        io.sockets.emit('updateusers', usernames);
        // echo globally that this client has left
        socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
    });

    // when the user sends a private msg to a user id, first find the username
    socket.on('check_user', function(asker, id){
        io.sockets.socket(usernames[asker]).emit('msg_user_found', check_key(id));
    });

    // when the user sends a private message to a user.. perform this
    socket.on('msg_user', function(usr, username, msg) {
        io.sockets.socket(usernames[usr]).emit('msg_user_handle', username, msg);
        io.sockets.socket(usernames[username]).emit('msg_user_handle', username, msg);
    });
});

client.js

var socket = io.connect('http://localhost:8008');   

//set username
var my_username = $("#user_data_for_mess").attr("my_username");
var username = $("#user_data_for_mess").attr("username");

// on connection to server, send user's name with an anonymous callback
socket.on('connect', function() {
    // call the server-side function 'adduser' and send one parameter (my_username)
    socket.emit('adduser', my_username);
});

// listener, whenever the server emits 'updatechat', this updates the chat body
socket.on('updatechat', function (username, data) {
    $('#show_conversation').append(data);
});

// listener, whenever the server emits 'msg_user_found'
socket.on('msg_user_found', function (username) {
    $('#message').keypress(function(e) {
        if(e.which == 13) {
            var message = $('#message').val();
            if($.trim(message).length != 0) {
                socket.emit('msg_user', username, my_username, message);
                $('#message').val('');
            }
        }
    });
});

socket.on('updateusers', function(data) {
    socket.emit('check_user', my_username, data[username]);
});

// listener, whenever the server emits 'msg_user_handle', this updates the chat body
socket.on('msg_user_handle', function (username, data) {
    $('#show_conversation').append(username + ": " + data);         
});

最佳答案

io.sockets.socket() - for emiting to specific clients
io.sockets.emit() - send to all connected clients (same as socket.emit)
io.sockets.on() - initial connection from a client.

socket.on() - event listener, can be called on client to execute on server
socket.emit() - send to all connected clients
socket.broadcast.emit() - send to all connected clients except the one that sent the message

你目前解决私信的方式没问题。我还在其他一些项目中使用了它,效果非常好。您也可能可以使用 socket.join() 来解决它

关于node.js - 套接字事件之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22424596/

相关文章:

java - 在java中获取用于tcp连接的开放套接字

node.js - 使用 Google CloudSQL,获取 "connect ECONNREFUSED 127.0.0.1:3306"

c# - X 交互后使用 TcpClient(套接字或流)通过网络发送和接收失败

node.js - 更新 Mongoose 中嵌套对象的单个数组值

java - 在不考虑计算资源的情况下,套接字可以处理的最大并发连接数是多少?

javascript - 没有端口号的 Socket.IO

python - django socketio - SocketIOHandler 错误

javascript - NodeJS函数被socketio事件中断

javascript - 获取Google云存储中特定目录内的所有文件和子目录

node.js - 使用 mysql 与express/Node : Is using globals ok?