6 # wrapped TCPSocket for communication with the server.
7 # emulates a subset of TCPSocket functionality
9 # total number of lines sent to the irc server
10 attr_reader :lines_sent
11 # total number of lines received from the irc server
12 attr_reader :lines_received
13 # server:: server to connect to
15 # host:: optional local host to bind to (ruby 1.7+ required)
16 # create a new IrcSocket
17 def initialize(server, port, host, sendfreq=2, maxburst=4)
24 @sendfreq = sendfreq.to_f
28 @last_send = Time.new - @sendfreq
31 @maxburst = maxburst.to_i
37 # open a TCP connection to the server
41 @sock=TCPSocket.new(@server, @port, @host)
42 rescue ArgumentError => e
43 $stderr.puts "Your version of ruby does not support binding to a "
44 $stderr.puts "specific local address, please upgrade if you wish "
45 $stderr.puts "to use HOST = foo"
46 $stderr.puts "(this option has been disabled in order to continue)"
47 @sock=TCPSocket.new(@server, @port)
50 @sock=TCPSocket.new(@server, @port)
56 @qthread = Thread.new { spooler }
60 def set_sendq(newfreq)
61 debug "changing sendq frequency to #{newfreq}"
62 @qmutex.synchronize do
64 if newfreq == 0 && @qthread
68 elsif(newfreq != 0 && !@qthread)
69 @qthread = Thread.new { spooler }
74 def set_maxburst(newburst)
75 @qmutex.synchronize do
88 # used to send lines to the remote IRCd
89 # message: IRC message to send
91 @qmutex.synchronize do
92 # debug "In puts - got mutex"
93 puts_critical(message)
97 # get the next line from the server (blocks)
104 debug "RECV: #{reply.inspect}"
110 @qmutex.synchronize do
111 # debug "QUEUEING: #{msg}"
115 # just send it if queueing is disabled
127 # pop a message off the queue, send it
131 if (now >= (@last_send + @sendfreq))
132 # reset burst counter after @sendfreq has passed
134 debug "in spool, resetting @burst"
135 elsif (@burst >= @maxburst)
136 # nope. can't send anything
139 @qmutex.synchronize do
140 debug "(can send #{@maxburst - @burst} lines, there are #{@sendq.length} to send)"
141 (@maxburst - @burst).times do
142 break if @sendq.empty?
143 puts_critical(@sendq.shift)
151 @qmutex.synchronize do
157 # flush the TCPSocket
162 # Wraps Kernel.select on the socket
164 Kernel.select([@sock], nil, nil, timeout)
167 # shutdown the connection to the server
174 # same as puts, but expects to be called with a mutex held on @qmutex
175 def puts_critical(message)
176 # debug "in puts_critical"
177 debug "SEND: #{message.inspect}"
178 @sock.send(message + "\n",0)
179 @last_send = Time.new