草庐IT

node.js - Socket.io + Redis - 客户端正在加入彼此的 "private"房间

coder 2023-07-19 原文

我刚刚开始使用 Socket.io 和 Redis 进行发布/订阅消息传递,它非常棒。我的应用程序的一个重要特性是服务器需要能够向一个房间的所有订阅者广播消息,并且还需要选择该房间中的 1 个订阅者并向他们窄播一条消息。目前,该订阅者是随机选择的。根据阅读 socket.io 的文档,我认为我可以做到这一点。

但是,我遇到了一些我不明白的事情。在 Socket.io 的默认房间文档 ( https://socket.io/docs/rooms-and-namespaces/#default-room ) 中,他们说每个套接字会自动加入一个以其套接字 ID 命名的房间。这看起来可以解决我的窄播需求——查看连接到我的“大”房间的客户端 ID 列表,随机选择一个,然后向与所选 ID 同名的房间发送一条消息。

但是,它不起作用,因为出于某种原因,所有客户端都加入了彼此的默认房间。我在我的代码中没有看到任何异常,但我的“窄播”消息将发送给所有客户端。

这是我的服务器端代码:

var io = require('socket.io');
var redisAdapter = require('socket.io-redis');
var server = io();

server.adapter(redisAdapter({ host: 'localhost', port: 6379 }))

server.on('connect', (socket) => {
  console.log(`${socket.id} connected!`);
  socket.join('new');
  server.emit('welcome', `Please give a warm welcome to ${socket.id}!`);
  server.to(socket.id).emit('private', 'Just between you and me, I think you are going to like it here');
});

server.listen(3000);

setInterval(whisperAtRandom, 2000);

function whisperAtRandom() {
  server.in('new').adapter.clients((err, clients) => {
    if (err) throw err;

    console.log('Clients on channel "new": ', clients);
    chosenOne = clients[Math.floor(Math.random()*clients.length)];
    console.log(`Whispering to ${chosenOne}`);
    server.to(chosenOne).emit('private', { message: `Psssst... hey there ${chosenOne}`});
    server.in(chosenOne).adapter.clients((err, clients) => {
      console.log(`Clients in ${chosenOne}: ${clients}`)
    })
  });
}

它启动服务器,监听端口 3000,然后每 2 秒向"new"房间中的随机客户端发送一条消息。它还会注销连接到"new"房间和“”房间的客户端列表。

这是客户端代码:

var sock = require('socket.io-client')('http://localhost:3000');

sock.connect();

sock.on('update', (data) => {
  console.log('Updating...');
  console.log(data);
});

sock.on('new', (data) => {
  console.log(`${sock.id} accepting request for new`);
  console.log(data.message);
});

sock.on('welcome', (data) => {
  console.log('A new challenger enters the ring');
  console.log(data);
});

sock.on('private', (data) => {
  console.log(`A private message for me, ${sock.id}???`);
  console.log(data);
});

我的问题是我所有的客户都连接到彼此的“”房间。这是我的日志中的示例:

0|socket-s | Clients on channel "new":  [ 'dJaoZd6amTfdQy5NAAAA', 'bwG1yTT46dr5R_G6AAAB' ]
0|socket-s | Whispering to bwG1yTT46dr5R_G6AAAB
2|socket-c | A private message for me, dJaoZd6amTfdQy5NAAAA???
2|socket-c | Psssst... hey there bwG1yTT46dr5R_G6AAAB
1|socket-c | A private message for me, bwG1yTT46dr5R_G6AAAB???
1|socket-c | Psssst... hey there bwG1yTT46dr5R_G6AAAB
0|socket-s | Clients in bwG1yTT46dr5R_G6AAAB: dJaoZd6amTfdQy5NAAAA,bwG1yTT46dr5R_G6AAAB

您可以看到“私有(private)”消息被两个客户端接收,dJaoZ...bwG1y...,并且两个客户端都连接到bwG1y... 的默认房间。

这是为什么?这与我的两个客户端都在同一台机器上运行(具有不同的 Node 进程)这一事实有关吗?我在 Socket.io 的文档中遗漏了什么吗?感谢您的帮助!

PS -- 更让人困惑的是,发生在 server.on('connect', ... 中的私有(private)消息传递有效!每个客户端都收到“就在你我之间...... ."仅在他们连接到服务器后立即发送一次消息。

最佳答案

您的主要问题可能是由 whisperAtRandom 函数中的 server.to 引起的,使用套接字而不是服务器来发送私有(private)消息:

socket.to(chosenOne).emit('private', { message: `Psssst... hey there ${chosenOne}`});

要回答您的其他问题,请尝试更改这些:

server.emit('welcome', `Please give a warm welcome to ${socket.id}!`);
server.to(socket.id).emit('private', 'Just between you and me, I think you are going to like it here');

收件人:

socket.broadcast.emit('welcome', `Please give a warm welcome to ${socket.id}!`);
socket.emit('private', 'Just between you and me, I think you are going to like it here');

查看我的 Socket.IO 备忘单:

// Socket.IO Cheatsheet

// Add socket to room
socket.join('some room');

// Remove socket from room
socket.leave('some room');

// Send to current client
socket.emit('message', 'this is a test');

// Send to all clients include sender
io.sockets.emit('message', 'this is a test');

// Send to all clients except sender
socket.broadcast.emit('message', 'this is a test');

// Send to all clients in 'game' room(channel) except sender
socket.broadcast.to('game').emit('message', 'this is a test');

// Send to all clients in 'game' room(channel) include sender
io.sockets.in('game').emit('message', 'this is a test');

// sending to individual socket id
socket.to(socketId).emit('hey', 'I just met you');

关于node.js - Socket.io + Redis - 客户端正在加入彼此的 "private"房间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50975031/

有关node.js - Socket.io + Redis - 客户端正在加入彼此的 "private"房间的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  3. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  4. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  5. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  6. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  7. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  8. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  9. ruby-on-rails - 相关表上的范围为 "WHERE ... LIKE" - 2

    我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que

  10. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

随机推荐