Ruby套接字没有收到所有消息

时间:2012-04-01 17:46:58

标签: ruby sockets irc

我在Ruby上编写了一个小脚本来连接和登录IRC服务器,但是当IRC服务器发出新消息时,套接字没有收到它,例如,日志是:

:irc.someserver.net NOTICE Auth :*** Looking up your hostname...
:irc.someserver.net NOTICE Auth :Welcome to someserver Net!
:irc.someserver.net 003 brobot :This server was created 15:40:35 Mar 28 2012
:irc.someserver.net 005 brobot MAXTARGETS=20 MODES=20 NETWORK=Studio NICKLEN=32 Net PREFIX=(ov)@+ STATUSMSG=@+ TOPICLEN=308 VBANLIST WALLCHOPS WALLVOICES :are supported by this server
:irc.someserver.net 372 brobot :- Welcome To the someserver Chat Server. Please Select the #Team Channel.
:irc.someserver.net 252 brobot 1 :operator(s) online
:irc.someserver.net 265 brobot :Current Local Users: 5  Max: 5
:irc.someserver.net 353 brobot = #brobot_dev :@Pablo brobot 
:Pablo!Pablo@ip-10-1-1-6.ec2.internal PRIVMSG #brobot_dev :f
PING :irc.someserver.net

这是一个示例日志,它看起来没问题,但在:Pablo!Pablo@ip-10-1-1-6.ec2.internal PRIVMSG #brobot_dev :f上就是它错过了消息。例如,我发送5条消息,客户端只接收1.这是客户端代码:

require 'socket'      # Sockets are in standard library

hostname = '10.1.1.1'
port = 6667

server = TCPSocket.open(hostname, port)

loop {
    server.flush
    puts server.gets.chomp

    if server.gets.chomp =~ /:.*NOTICE Auth :\*\*\* Found your hostname/
        server.puts "USER brobot brobot brobot brobot\r\nNICK brobot\r\n"
    elsif server.gets.chomp =~ /:\S* 26*/
        server.puts "JOIN #brobot_dev\r\n"
    end
}

我做错了什么?谢谢!

1 个答案:

答案 0 :(得分:0)

问题在于

puts server.gets.chomp

收集服务器发送的数据,打印并丢弃。然后你每次再调用两次相同的东西,每次收集新数据。试试这个:

@response = server.gets.chomp
# use contents of @response instead of calling #gets again
if @response =~ /:.*NOTICE Auth :\*\*\* Found your hostname/
    server.print "USER brobot brobot brobot brobot\r\nNICK brobot\r\n"
elsif @response =~ /:\S* 26*/
    server.print "JOIN #brobot_dev\r\n"
end

我已将'puts'替换为'print',因为你在字符串中包含了\ r \ n。