-
-
Save benoittgt/aaa7a90841b61ce695cf38b6ef9a0a1c to your computer and use it in GitHub Desktop.
HTTP server using Ractors (Ruby 3)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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