【问题标题】:Ruby XMPP4R bot and Threads - troubleRuby XMPP4R 机器人和线程 - 麻烦
【发布时间】:2011-05-30 01:22:35
【问题描述】:

我希望我的机器人在并行线程中发送和接收消息。我还希望我的机器人在收到用户的任何消息时将消息发送回用户。但现在他每 5 秒将其发回给用户。我知道这是因为我使用了“循环执行”但没有无限循环我不能使用回调。 那么如何在并行线程中发送和接收消息呢?以及接收消息时如何克服我的“循环问题”?

require 'xmpp4r'

class Bot
    include Jabber

    def initialize jid,jpassword
        @jid = jid
        @jpassword = jpassword

        @client = Client.new(JID::new(@jid))
        @client.connect
        @client.auth(@jpassword)
        @client.send(Presence.new.set_type(:available))
    end

    def wait4msg
        loop do
            @client.add_message_callback do |msg|               
                send_message(msg.from,msg.body)
                sleep 5
            end
        end
    end 

    def send_message to,message
        msg = Message::new(to,message)
        msg.type = :chat
        @client.send(msg)
    end

    def add_user jid
        adding = Presence.new.set_type(:subscribe).set_to(jid)
        @client.send(adding)
    end
end

bot = Bot.new('from@example.xmpp','123456')
t1 = Thread.new do
    bot.wait4msg
end

t2 = Thread.new do
    bot.send_message('to@example.xmpp',Random.new.rand(100).to_s)
end

Thread.list.each { |t| t.join if t != Thread.main }

【问题讨论】:

    标签: multithreading xmpp4r


    【解决方案1】:

    美好的一天。您可以使用没有循环的回调,请参阅示例。例如:在initialize添加

    @client.add_message_callback do |m|
      if m.type != :error
        m2 = Message.new(m.from, "You sent: #{m.body}")
        m2.type = m.type
        @client.send(m2)
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2013-02-13
      • 2012-08-23
      • 1970-01-01
      • 2015-09-17
      • 2011-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多