【问题标题】:Faye Websocket Ruby not working as expectedFaye Websocket Ruby 没有按预期工作
【发布时间】:2020-09-05 19:40:01
【问题描述】:

我正在尝试使用 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 开发工具

请帮帮我!!!

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

如前所述。下面的代码成功

puts "sent" if ws.send(msg)

【问题讨论】:

    标签: ruby websocket haproxy faye


    【解决方案1】:

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

    改变这个

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

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

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

    【讨论】:

    • 保持活动 (ping) 与您的信息更新频率无关。 Keep alive (ping) 将流量添加到安静的连接中,这样中介(例如 HAProxy)就不会终止连接。一个合理的值是 50 秒,因为大多数中介将在不到一分钟后终止连接。您可能需要检查您的 HAProxy 设置并设置一个合理的值。
    猜你喜欢
    • 2018-05-22
    • 1970-01-01
    • 2012-02-06
    • 2021-10-19
    • 2020-03-18
    • 2012-06-14
    • 2014-11-15
    • 1970-01-01
    • 2012-07-02
    相关资源
    最近更新 更多