gpt4 book ai didi

javascript - 如何向在socket.io中的不同选项卡或浏览器中打开的同一用户发出事件?

转载 作者:太空宇宙 更新时间:2023-11-03 22:32:05 25 4
gpt4 key购买 nike

我发现通过创建空间它可以被执行..但有些地方出了问题。

服务器端:-

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


http.listen(3000, function(){
console.log('listening on *:3000');
});

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

socket.on('Init', function(data){
if(data in users){

var roomName = 'room'+ data;
var index = rooms.indexof(roomName);
if(rooms.notContain(roomName)){
rooms.push(roomName);
var index = rooms.indexof(roomName);
users[data].join(rooms[index]);
socket.join(rooms[index]);
}else{
socket.join(rooms[index]);
}
}else{
socket.username = data;
users[socket.username] = socket;
}

var indo = rooms.indexof('room'+ data);
socket.in(rooms[indo]).emit('hai', data);
});
});

Array.prototype.indexof = function(Obj){
return this.indexOf(Obj);
}
Array.prototype.notContain = function(Obj){
for(i in this){
if(this[i] === Obj) return false;
}
return true;
}

客户端:-

var socket = io.connect('http://localhost:3000', { 'forceNew': true});
var userId = '<?php echo $_GET['userId'] ?>';
socket.on('connect', function(){
socket.emit('Init', userId);
});
socket.on('hai', function(data){
alert(data);
});

请检查此问题或向我提供任何其他解决方案来解决此问题。我希望同一用户发出在不同浏览器或选项卡中打开的信号。

最佳答案

我猜您正在尝试向同一用户的所有连接发送消息。这是一种方法:

var user_sockets = {};
io.on('connection', function(socket){
socket.on('Init', function(data){
if (typeof user_sockets[data] === 'undefined') {
user_sockets[data] = [];
}

user_sockets[data].push(socket);
for (var i = 0; i < user_sockets[data].length; i++) {
var s = user_sockets[data][i];
s.emit('hai', data);
}
});
});

关于javascript - 如何向在socket.io中的不同选项卡或浏览器中打开的同一用户发出事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35315096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com