簡體   English   中英

Ruby-從多個套接字讀取(IRC機器人)

[英]Ruby - Reading from multiple sockets (irc bot)

我正在嘗試制作一個可以連接到多個服務器的IRC機器人,但是我無法一次從所有套接字讀取信息。

我當前的代碼:

#!/usr/bin/ruby
    require 'socket'

    servers = ["irc.chat4all.org"]

    def connect(server, port, count)
            puts "connecting to #{server}..."
                    @socket[count] = TCPSocket.open(server, port)
                    say("NICK link_hub", count)
                    say("USER link_hub 0 * link_hub", count)
                    read_data(count)
    end

    def say(msg, count)
            @socket[count.to_i].puts msg.to_s
    end

    def say_channel(msg, count)
            @socket[count.to_i].puts("PRIVMSG #test :"+msg.to_s)
    end


    def read_data(count)
            until @socket[count].eof? do
                    msg = @socket[count].gets
                    puts msg
                    if msg.match(/^PING :(.*)$/)
                            say("PONG #{$~[1]}", count)
                            say("JOIN #test", count)
                            next
                    end
                    if msg.match(/`test/)
                            say_channel("connecting to efnet...", count)
                            Thread.new {
                            connect("irc.efnet.nl", 6667, count)
                            }
                    end
            end
    end

    conn = []
    count = 0
    @socket = []
    servers.each do |server|
            connect(server, 6667, count)
            count += 1
    end

問題是當我發送命令'test'時,它連接到efnet,但是即使我在線程中運行新連接,它也不會再讀取其他套接字。 我只想同時讀取兩個套接字。 (變量“ count”是套接字號)

誰能幫我嗎? 非常感激!

為此,您需要並行處理。

pids = []
servers.each do |server|
    pids << fork do
      connect(server, 6667, count)
      count += 1
    end
end
pids.each{|pid| Process.wait pid}

您可能需要閱讀有關流程,線程和其他操作系統主題的信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM