gpt4 book ai didi

ruby - celluloid-io 或带有蚊子循环的 eventmachine

转载 作者:数据小太阳 更新时间:2023-10-29 06:55:04 26 4
gpt4 key购买 nike

我正在构建一个小的 ruby​​ 程序来运行与 MQTT 的连接。服务器并订阅 channel 。我正在使用 mosquitto gem 这只是 libmosquitto 的桥梁C 库。

我创建了一个非常简单的程序实现,可以使用 ruby my_prog.rb 运行:

# Dependencies

require File.expand_path(File.join('..', 'environment'), __FILE__)


# MQTT Application

module Pulsr
class MQTT
attr_reader :host, :port, :alive

def initialize(host = 'iot.eclipse.org', port = 1883, alive = 60)
@client ||= Mosquitto::Client.new SecureRandom.hex(8)

Signal.trap(Signal.list.has_key?('INT') ? 'SIGINT' : 'SIGTERM') do
@client.log 'Shutdown'
shutdown
end

@host = host
@port = port
@alive = alive

start
end


private

def on_connect
Proc.new { |return_code|
@client.log "Connected RC #{return_code}"

@client.subscribe(nil, '/pulsr', Mosquitto::EXACTLY_ONCE)
}
end

def on_disconnect
Proc.new { |return_code| @client.log "Disconnected RC #{return_code}" }
end

def on_subscribe
Proc.new { |message_id, granted_qos| @client.log "Subscribed MID #{message_id} QoS #{granted_qos}" }
end

def on_unsubscribe
Proc.new { |message_id| @client.log "Unsubscribed MID #{message_id}" }
end

def on_message
Proc.new { |message| Pulsr::Workers::TrackingEvent.perform_async message.to_s }
end

def configure
@client.logger = Logger.new(STDOUT)

@client.on_connect &on_connect
@client.on_disconnect &on_disconnect
@client.on_subscribe &on_subscribe
@client.on_unsubscribe &on_unsubscribe
@client.on_message &on_message
end

def connect
@client.connect_async(@host, @port, @alive)
end

def start
@client.loop_start

configure
connect

sleep
end

def shutdown
@client.loop_stop(true)
Process.exit
end
end
end


# MQTT Start

Pulsr::MQTT.new :host => 'iot.eclipse.org', :port => 1883, :alive => 60

我想知道,如果我想使用 CelluloidEventMachine要运行 mosquitto gem 提供的循环,我该怎么做?

mosquitto gem 提供了一个很好的documentation并介绍了一些可以使用的循环方法,但我不知道从哪里开始或如何开始,我也没有使用过 EM 或 Celluloid。

任何人都可以帮助开始这个,我认为它可以为社区带来一些值(value),它最终可以成为一个开源项目,对 mosquitto gem 的一个小补充?

最佳答案

我觉得没那么难。Mosquitto 有一个很好的库。

你需要连接这些函数:

mosquitto_loop_misc() <-> EventMachine::PeriodicTimer.new
mosquitto_read() <-> EventMachine.watch
mosquitto_write() <-> EventMachine.watch

关于ruby - celluloid-io 或带有蚊子循环的 eventmachine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23757435/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com