7 # wrapped TCPSocket for communication with the server.
8 # emulates a subset of TCPSocket functionality
10 # total number of lines sent to the irc server
11 attr_reader :lines_sent
13 # total number of lines received from the irc server
14 attr_reader :lines_received
16 # delay between lines sent
17 attr_reader :sendq_delay
20 attr_reader :sendq_burst
22 # server:: server to connect to
24 # host:: optional local host to bind to (ruby 1.7+ required)
25 # create a new IrcSocket
26 def initialize(server, port, host, sendq_delay=2, sendq_burst=4)
27 @timer = Timer::Timer.new
38 @sendq_delay = sendq_delay.to_f
42 @last_send = Time.new - @sendq_delay
45 @sendq_burst = sendq_burst.to_i
51 # open a TCP connection to the server
55 @sock=TCPSocket.new(@server, @port, @host)
56 rescue ArgumentError => e
57 $stderr.puts "Your version of ruby does not support binding to a "
58 $stderr.puts "specific local address, please upgrade if you wish "
59 $stderr.puts "to use HOST = foo"
60 $stderr.puts "(this option has been disabled in order to continue)"
61 @sock=TCPSocket.new(@server, @port)
64 @sock=TCPSocket.new(@server, @port)
71 def sendq_delay=(newfreq)
72 debug "changing sendq frequency to #{newfreq}"
73 @qmutex.synchronize do
74 @sendq_delay = newfreq
84 def sendq_burst=(newburst)
85 @qmutex.synchronize do
86 @sendq_burst = newburst
90 # used to send lines to the remote IRCd
91 # message: IRC message to send
93 @qmutex.synchronize do
94 # debug "In puts - got mutex"
95 puts_critical(message)
99 # get the next line from the server (blocks)
103 reply.strip! if reply
104 debug "RECV: #{reply.inspect}"
110 @qmutex.synchronize do
115 # just send it if queueing is disabled
120 # pop a message off the queue, send it
127 if (now >= (@last_send + @sendq_delay))
128 # reset burst counter after @sendq_delay has passed
130 debug "in spool, resetting @burst"
131 elsif (@burst >= @sendq_burst)
132 # nope. can't send anything, come back to us next tick...
136 @qmutex.synchronize do
137 debug "(can send #{@sendq_burst - @burst} lines, there are #{@sendq.length} to send)"
138 (@sendq_burst - @burst).times do
139 break if @sendq.empty?
140 puts_critical(@sendq.shift)
150 @qmutex.synchronize do
156 # flush the TCPSocket
161 # Wraps Kernel.select on the socket
162 def select(timeout=nil)
163 Kernel.select([@sock], nil, nil, timeout)
166 # shutdown the connection to the server
173 # same as puts, but expects to be called with a mutex held on @qmutex
174 def puts_critical(message)
175 # debug "in puts_critical"
176 debug "SEND: #{message.inspect}"
177 @sock.send(message + "\n",0)
178 @last_send = Time.new