Sha256: 290e18820e139d5bc35e6328a4a7e7c4d9c5c4f148096066f17e484d1458e70c

Contents?: true

Size: 1.1 KB

Versions: 2

Compression:

Stored size: 1.1 KB

Contents

# frozen_string_literal: true

require 'bundler/setup'
require 'polyphony'
require 'http/parser'

class Http::Parser
  def setup_async
    self.on_message_complete = proc { @request_complete = true }
  end

  def parse(data)
    self << data
    return nil unless @request_complete

    @request_complete = nil
    self
  end
end

def handle_client(socket)
  parser = Http::Parser.new
  req = nil
  parser.on_message_complete = proc do |env|
    req = parser
  end
  while (data = socket.readpartial(8192)) do
    parser << data
    if req
      handle_request(socket, req)
      req = nil
      snooze
    end
  end
rescue IOError, SystemCallError => e
  # do nothing
ensure
  socket.close rescue nil
  parser.reset!
end

def handle_request(client, parser)
  status_code = 200
  data = "Hello world!\n"
  headers = "Content-Length: #{data.bytesize}\r\n"
  client.write "HTTP/1.1 #{status_code}\r\n#{headers}\r\n#{data}"
end

spin do
  server = TCPServer.open('0.0.0.0', 1234)
  puts "listening on port 1234"

  loop do
    client = server.accept
    spin { handle_client(client) }
  end
end

puts "pid #{Process.pid}"
suspend

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
polyphony-0.26 examples/performance/thread-vs-fiber/polyphony_server.rb
polyphony-0.25 examples/performance/thread-vs-fiber/polyphony_server.rb