On 08.10.2007 17:03, kazaam wrote:
hmm I wanted to use it because I have many different server sockets. They are created in a fork.
What exactly do you mean by that? If you create them in a sub process
then you just have one pair per process - do you?
I did it now with your loop and it seems to work now except the fact the browsing through my webproxy is now pretty slow and I’m getting really confusing errors:
./httpsocket.rb:23:in readline': end of file reached (EOFError) from ./httpsocket.rb:23 ./httpsocket.rb:23:in
readline’: end of file reached (EOFError)
from ./httpsocket.rb:23
./httpsocket.rb:23:in readline': end of file reached (EOFError) from ./httpsocket.rb:23 ./httpsocket.rb:23:in
readline’: end of file reached (EOFError)
from ./httpsocket.rb:23
That’s why:
http://www.ruby-doc.org/core/classes/IO.html#M002298
$bind_port = ‘23322’
$bind_address=‘localhost’
opens a socket on the local machine and binds the proxy to it
proxy = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
proxy.bind(Socket.pack_sockaddr_in($bind_port, $bind_address ))
proxy.listen(1)
Why don’t you use TCPServer? Seems much easier for your use case.
There is a comprehensive example in the Pickaxe.
waits for Browser-client connections
while client = proxy.accept
fork()
I believe you are not using fork properly here. The easiest is to use
it with a block which gets executed in the child. If you do not do
that, you need to evaluate the return value of fork to determine whether
you are in the parent or child process.
# reads the browsers request
request=''
while client[0].readline
request += $_
break if $_ =~ /^\s*$/m
if $_ =~ /^GET .+/
host = URI.parse(URI.extract($_)[0]).host
port = URI.parse(URI.extract($_)[0]).port
end
end
Why don’t you read the complete request? This way you can’t do POST and
PUT as far as I can see.
# connects to the webserver and sends the request
server = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
server.connect(Socket.pack_sockaddr_in(port, host.chomp.sub('/','') ))
server.write(request)
TCPSocket seems easier here.
# reads webservers response
response=''
while server.readline
response += $_
break if $_ =~ /^\s*$/m
end
You’re making your life much harder than necessary. Why don’t you just
do this
response = “”
server.each do |line|
response << line
break if /^\s*$/m =~ line
end
or
response = “”
while line = server.gets
response << line
break if /^\s*$/m =~ line
end
# sends the http-header to browser
client[0].write(response)
# listens for further responses of the server and sends it to the browser
while ( response = server.read(2**16) )
client[0].write(response)
end
end
It seems you are trying to write a HTTP proxy. If it is not for the
educational experience then I suggest to look into the RAA or in the
standard lib. I believe a proxy class is part of Webrick.
Kind regards
robert