Nafaa Boutefer
Nafaa Boutefer

Reputation: 2359

how multiprocesses/multithreads Ruby Web Servers work?

the following code is a simulation of a web server that has 3 workers (processes) and for each new connection the selected worker creates a new thread. What I cannot understand is how a worker is selected to respond to a comming connection? and how all the three workers are listening to a similar port without a problem.

require 'socket'
require 'thread'

server = TCPServer.new('0.0.0.0', 8080)
3.times do
 break unless fork
end

loop do
 connection = server.accept
 Thread.new do
        request = connection.gets

        connection.puts request
        connection.puts Process.pid.to_s # this will change with each request.
        connection.puts "status"
        connection.puts "Headers"
        connection.puts "Body"
        connection.close
 end
end

Upvotes: 1

Views: 156

Answers (1)

Uri Agassi
Uri Agassi

Reputation: 37409

A TCP server listens to a port, waiting for a new connection request. When one comes, it creates a dedicated socket for the specific client (on another port), hands it off to a worker, and resumes listening to main port.

connection = server.accept

The above line is the line where a worker tells the server "I'm ready to receive a new socket", and the server will return the socket that it created for the latest client request.

If more than one worker is waiting for a new socket (all call server.accept) the server chooses one of them (it is not supposed to be important which one, but the obvious implementation is "first in first served"), and the rest simply wait for the next request...

Upvotes: 2

Related Questions