Sha256: 18c99b3f788a4f8ff6ee39d8de1d7a7975ab836f780ecff001ac16978920a02a

Contents?: true

Size: 958 Bytes

Versions: 2

Compression:

Stored size: 958 Bytes

Contents

# frozen_string_literal: true

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

$connection_count = 0

def handle_client(socket)
  $connection_count += 1
  parser = Http::Parser.new
  reqs = []
  parser.on_message_complete = proc do |env|
    reqs << Object.new # parser
  end
  socket.read_loop do |data|
    parser << data
    while (req = reqs.shift)
      handle_request(socket, req)
      req = nil
      snooze
    end
  end
rescue IOError, SystemCallError => e
  # do nothing
ensure
  $connection_count -= 1
  socket&.close
end

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

server = TCPServer.open('0.0.0.0', 1234)
puts "pid #{Process.pid}"
puts "listening on port 1234"

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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
polyphony-0.45.5 examples/performance/thread-vs-fiber/polyphony_server.rb
polyphony-0.45.4 examples/performance/thread-vs-fiber/polyphony_server.rb