Reading from multiple sockets (irc bot)

I'm trying to make an IRC bot that connects to multiple servers, and I'm having trouble reading from all the sockets at once.

My current code:


    #!/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
    

The problem is that when I send the command '`test', it connects to efnet, but it wont read the other socket anymore even though im running the new connection in a thread. I just want to read from both sockets at the same time. (the variable 'count' is the socket number)

Can anyone help me out? Much appreciated!


You need paralelism for that.

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

You might want to read about processes, threads and other operational system topics.

链接地址: http://www.djcxy.com/p/53462.html

上一篇: IRC:无身份响应

下一篇: 从多个套接字读取(irc bot)