ruby - 如何在 websocket eventmachine 中断开 redis 客户端

标签 ruby websocket redis eventmachine

我正在尝试构建一个 websocket 服务器,每个客户端在其中建立自己的用于发布和订阅的 redis 连接。

当redis服务器运行时,当客户端连接到websocket服务器时,我可以看到正在建立的两个新连接,我也可以向客户端发布数据,但是当客户端断开与websocket服务器的连接时,我也想要断开与 Redis 的连接。我该怎么做?

也许我做错了,但这是我的代码。

#require 'redis'
require 'em-websocket'
require 'em-hiredis'
require 'json'

CLIENTS = Hash.new

class PubSub
  def initialize(client)
    @socket = client.ws
    # These clients can only be used for pub sub commands
    @publisher = EM::Hiredis.connect #Later I will like to disconnect this
    @subscriber = EM::Hiredis.connect #Later I will like to disconnect this
    client.connections << @publisher << @subscriber
  end
  def subscribe(channel)
    @channel = channel
    @subscriber.subscribe(channel)
    @subscriber.on(:message) { |chan, message|
      @socket.send message
    }
  end
  def publish(channel,msg)
    @publisher.publish(channel, msg).errback { |e|
      puts [:publisherror, e]
    }
  end
  def unsubscribe()
    @subscriber.unsubscribe(@channel)
  end
end

class Client
  attr_accessor :connections, :ws
  def initialize(ws)
    @connections = []
    @ws = ws
  end
end

EventMachine.run do
  # Creates a websocket listener
  EventMachine::WebSocket.start(:host => '0.0.0.0', :port => 8081) do |ws|

    ws.onopen do
      # I instantiated above
      puts 'CLient connected. Creating socket'      
      @client = Client.new(ws)
      CLIENTS[ws] = @client
    end

    ws.onclose do
      # Upon the close of the connection I remove it from my list of running sockets
      puts 'Client disconnected. Closing socket'

      @client.connections.each do |con|
        #do something to disconnect from redis
      end

      CLIENTS.delete ws
    end

    ws.onmessage { |msg|
      puts "Received message: #{msg}"
      result = JSON.parse(msg)
      if result.has_key? 'channel'
        ps = PubSub.new(@client)
        ps.subscribe(result['channel'])
      elsif result.has_key? 'publish'
         ps = PubSub.new(ws)
         ps.publish(result['publish']['channel'],result['publish']['msg']);
      end
    }
  end
end

最佳答案

这个版本的em-hiredis支持关闭连接:https://github.com/whatupdave/em-hiredis

关于ruby - 如何在 websocket eventmachine 中断开 redis 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7255364/

相关文章:

ruby-on-rails - Nginx可以用作后端Websocket服务器的反向代理吗?

redis - 使用 Redis 计算给定时间窗口内的共现次数

python - Redis channels -- 抓取key时的WRONGTYPE操作

java - 如何从Redis客户端获取ttl Redisson键值

ruby - 通过 Apache mod_fcgid 服务的 Redmine 2.4.2 返回错误 500

node.js - 使用socket.io发送特定消息到特定socket.id

ruby - 使用 gdb 错误 : evaluation of this expression requires the program to have a function "malloc" 调试 ruby​​ 程序

http - websockets 必须有心跳吗?

ruby - 如何在 Roda 中获取客户端的 IP 地址?

ruby - ENOENT 在 Ruby 中创建 UNIX 套接字时