Faye Websocket Ruby无法正常工作

问题描述

我正在尝试使用haproxy来平衡我的websocket机架应用程序。

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

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

但是,客户端永远不会在频道“费率”中收到发布的消息。

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,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,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开发者工具

enter image description here

请帮助我!

编辑: 我已经尝试过Thread running in Middleware is using old version of parent's instance variable,但这不起作用。

如前所述。以下代码成功

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,因为我正在申请一个价格变化非常快的股票申请。您可以根据需要保留它。