javascript - 如何使用 socket.io 发出一个在连接的客户端之间更新的数组
问题描述
我正在尝试通过将用户名添加到数组中来显示聊天室中所有已连接客户端的用户名。目前,我的代码只会使用最近加入的用户名更新用户列表,而不是将用户名添加到数组中,这让我相信数组实际上并没有按照我预期的方式发出?
脚本.js:
var items = [];
var user = user;
if (!user) {
user = prompt('Please choose a username:');
items.push(user);
socket.emit('theitems', {
items: items
});
if (!user) {
alert('Your name has been set to "Anonymous"');
user = "Anonymous"
items.push(user);
} else {
alert('Your name has been set to "'+ user +'"');
}
}
console.log(items);
socket.on('theitems', function (data) {
$('.dispUser').html(data.items);
});
index.js
server(socket('theitems', ctx => { console.log(ctx.data); ctx.io.emit('theitems', ctx.data); }));
更新了将服务器用作“主阵列”的代码。
这段代码(+上面的一些)解决了我的问题。
index.js(服务器):
var newitems = [];
server(socket('theitems', ctx => { newitems.push(ctx.data); console.log(ctx.data); ctx.io.emit('theitems', newitems); }));
script.js(客户端):
socket.emit('theitems', user);
socket.on('theitems', function (data) {
$('.dispUser').html(data);
console.log(data);
});
解决方案
很简单,只要socket.emit('eventName', array);
但是,如果您更改数组项,则不会在所有套接字客户端和/或服务器中更改。每次数组更改时,您都需要发出新数组。否则套接字不会更新它们的值
推荐阅读
- flutter - 提供者,将其分配给变量和直接使用它有什么区别?
- python - Beautifulsoup 的 Python 抓取问题
- ios - 如何在将其转换为 Double 之前检查字符串值是否为 nil
- reactjs - 为什么react useQuery() 在突变后不获取最新数据?
- mysql - Laravel 7.4 无法添加外键约束
- kubernetes - Kubernetes中如何定义微服务自注册地址给consul
- javascript - 已经登录,但我仍然收到此错误“缺少权限或权限不足”。
- javascript - Swiper - 找不到依赖打字稿,离子-vue
- http - 在为多个 goroutine 使用单个 http 客户端时,在一个线程上编辑传输会影响另一个线程吗?
- rust - Tokio mpsc 接收器上的非阻塞接收