Skip to content

Instantly share code, notes, and snippets.

@leandronsp
Created February 15, 2023 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leandronsp/fbc605d583a92d376267f9170f09e514 to your computer and use it in GitHub Desktop.
Save leandronsp/fbc605d583a92d376267f9170f09e514 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