Skip to content

Instantly share code, notes, and snippets.

@benoittgt
Forked from leandronsp/server.rb
Created July 11, 2024 11:40
Show Gist options
  • Save benoittgt/aaa7a90841b61ce695cf38b6ef9a0a1c to your computer and use it in GitHub Desktop.
Save benoittgt/aaa7a90841b61ce695cf38b6ef9a0a1c to your computer and use it in GitHub Desktop.
HTTP server using Ractors (Ruby 3)
require 'socket'
@queue = Ractor.new do
loop do
Ractor.yield(Ractor.receive, move: true)
end
end
listener = Ractor.new(@queue) do |queue|
socket = TCPServer.new(PORT)
puts "Listening to the port #{PORT}..."
loop do
client = socket.accept
queue.send(client, move: true)
end
end
workers = CPUS.times.map do
Ractor.new(@queue) do |queue|
loop do
client = queue.take
client.puts("HTTP/1.1 200\r\nContent-Type: text/html\r\n\r\n<h1>Yo</h1>")
client.close
end
end
end
loop do
Ractor.select(listener, *workers)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment