TCP server with Thread per connection
Three lines of substance: TCPServer.new opens the port. accept loops. Thread.new spawns one MRI thread per connection. Done.
require 'socket'
server = TCPServer.new('127.0.0.1', 6380)
loop do
client = server.accept
Thread.new(client) do |conn|
begin
while (data = conn.recv(4096)) && !data.empty?
conn.write(data)
end
rescue IOError, Errno::ECONNRESET
ensure
conn.close rescue nil
end
end
endThe entire echo server. The GIL serialises bytecode but releases on recv, so threads cooperate.
The GIL serialises Ruby bytecode execution, but it releases during blocking IO (recv, write, sleep). For a network server, that means threads effectively cooperate: one is waiting on IO, another runs bytecode. CPU-bound work would hit the GIL ceiling; IO-bound work does not.
Quiz: Quiz
Loading practice…