Faye Websocket Ruby 未按预期工作

Faye Websocket Ruby not working as expected

我正在尝试使用 haproxy 对我的 websocket 机架应用程序进行负载平衡。

我使用 redis-cli 在频道 rates 中发布消息并成功 puts "sent" if ws.send(msg)

客户端确实收到了 'Welcome! from server' 消息,所以我知道初始握手已完成。

但是,客户端从未收到频道'rates'中发布的消息。

web_socket.rb

require 'faye/websocket'

module WebSocket
 class App
   KEEPALIVE_TIME = 15 # in seconds

def initialize(app)
  @app     = app
  @mutex = Mutex.new
  @clients = []
  # @redis   = Redis.new(host: 'rds', port: 6739)
  Thread.new do
    @redis_sub = Redis.new(host: 'rds', port: 6379)
    @redis_sub.subscribe('rates') do |on|
      on.message do |channel, msg|
        p [msg,@clients.length]
        @mutex.synchronize do
          @clients.each do |ws|
            # ws.ping 'Mic check, one, two' do
            p ws
            puts "sent" if ws.send(msg)
            # end
          end
        end
      end
    end
  end
end

def call(env)
  if Faye::WebSocket.websocket?(env)
    # WebSockets logic goes here
    ws = Faye::WebSocket.new(env, nil) # {ping: KEEPALIVE_TIME }
    ws.on :open do |event|
      p [:open,  ENV['APPID'], ws.object_id]
      ws.ping 'Mic check, one, two' do
        # fires when pong is received
        puts "Welcome sent" if ws.send('Welcome! from server')
        @mutex.synchronize do
          @clients << ws
        end
        p [@clients.length, ' Client Connected']
      end

    end
    ws.on :close do |event|
      p [:close, ENV['APPID'], ws.object_id, event.code, event.reason]
      @mutex.synchronize do
        @clients.delete(ws)
      end
      p @clients.length
      ws = nil
    end
    ws.on :message do |event|
      p [:message, event.data]
      # @clients.each {|client| client.send(event.data) }
    end
    # Return async Rack response
    ws.rack_response
  else
    @app.call(env)
  end
  end
  end
  end

我的haproxy.cfg

frontend http
  bind *:8080
  mode http
  timeout client 1000s
  use_backend all
backend all
  mode http
  timeout server 1000s
  timeout tunnel 1000s
  timeout connect 1000s
  server s1 app1:8080
  server s2 app2:8080
  server s3 app3:8080
  server s4 app4:8080

Chrome 开发工具

请帮帮我!!!

编辑: 我试过 但这不起作用。

如前所述。以下代码成功

puts "sent" if ws.send(msg)

好的,经过大量的搜索和测试..我发现问题出在没有设置ping。在服务器的 websocket 初始化期间。

改变这个

ws = Faye::WebSocket.new(env, nil) # {ping: KEEPALIVE_TIME }

ws = Faye::WebSocket.new(env, nil, {ping: KEEPALIVE_TIME })

我的 KEEPALIVE_TIME 是 0.5,因为我正在制作利率变化非常快的股票申请。您可以根据需要保留它。