所以见证并观察下面的代码,我的问题是为什么在send_to_server中启动cool.io循环之后我从未进入on_connect,l.run应根据github上的文档示例触发请求,以及代码如何处理模块服务器@socket.attach(l)
l.run
它可以正常工作并接受传入的数据并将其发送到我的解析器,解析器可以正常工作并一直触发,直到前面提到的send_to_server。那么这里发生了什么?
require 'cool.io'
require 'http/parser'
require 'uri'
class Hash
def downcase_key
keys.each do |k|
store(k.downcase, Array === (v = delete(k)) ? v.map(&:downcase_key) : v)
end
self
end
end
module ShadyProxy
extend self
module ClientParserCallbacks
extend self
def on_message_complete(conn)
lambda do
puts "on_message_complete"
PluginHooks.before_request_to_server(conn)
end
end
def on_headers_complete(conn)
lambda do |headers|
conn.headers = headers
end
end
def on_body(conn)
lambda do |chunk|
conn.body << chunk
end
end
end
module PluginHooks
extend self
def before_request_to_server(conn)
# modify request here
conn.parser.headers.delete "Proxy-Connection"
conn.parser.headers.downcase_key
send_to_server(conn)
end
def send_to_server(conn)
parser = conn.parser
uri = URI::parse(parser.request_url)
l = Coolio::Loop.default
puts uri.scheme + "://" + uri.host
c = ShadyHttpClient.connect(uri.scheme + "://" + uri.host,uri.port).attach(l)
c.connection_reference = conn
c.request(parser.http_method,uri.request_uri)
l.run
end
def before_reply_to_client(conn)
end
end
class ShadyHttpClient < Coolio::HttpClient
def connection_reference=(conn)
puts "haz conneciton ref"
@connection_reference = conn
end
def connection_reference
@connection_reference
end
def on_connect
super
#never gets here
@headers = nil
@body = ''
@buffer = ''
end
def on_connect_failed
super
# never gets here either
end
def on_response_header(header)
@headers = header
end
def on_body_data(data)
puts "on data?"
@body << data
STDOUT.write data
end
def on_request_complete
puts "Headers"
puts @headers
puts "Body"
puts @body
end
def on_error(reason)
STDERR.puts "Error: #{reason}"
end
end
class ShadyProxyConnection < Cool.io::TCPSocket
attr_accessor :headers, :body, :buffer, :parser
def on_connect
@headers = nil
@body = ''
@buffer = ''
@parser = Http::Parser.new
@parser.on_message_complete = ClientParserCallbacks.on_message_complete(self)
@parser.on_headers_complete = ClientParserCallbacks.on_headers_complete(self)
@parser.on_body = ClientParserCallbacks.on_body(self)
end
def on_close
puts "huh?"
end
def on_read(data)
@buffer << data
@parser << data
end
end
module Server
def run(opts)
begin
# Start our server to handle connections (will raise things on errors)
l = Coolio::Loop.new
@socket = Cool.io::TCPServer.new(opts[:host],opts[:port], ShadyProxy::ShadyProxyConnection)
@socket.attach(l)
l.run
# Handle every request in another thread
loop do
Thread.new s = @socket.accept
end
# CTRL-C
rescue Interrupt
puts 'Got Interrupt..'
# Ensure that we release the socket on errors
ensure
if @socket
@socket.close
puts 'Socked closed..'
end
puts 'Quitting.'
end
end
module_function :run
end
end
ShadyProxy::Server.run(:host => '0.0.0.0',:port => 1234)