Skip to content

Instantly share code, notes, and snippets.

@ytnk531

ytnk531/fiber_server.rb Secret

Created Oct 21, 2020
Embed
What would you like to do?
require 'socket'
require 'nio'
module FiberServer
#:nodec:
class Server
def initialize
@selector = NIO::Selector.new
@fibers = {}
end
def run
@srv = TCPServer.new 13_000
@selector.register @srv, :r
loop do
@selector.select do |m|
case m.io
when @srv
accept m.io
else
communicate m.io
end
end
end
end
def accept(io)
socket = io.accept_nonblock
@fibers[socket] = communication_fiber
@selector.register socket, :r
end
def communicate(io)
f = @fibers[io]
@selector.deregister io
f.resume io
end
def communication_fiber
Fiber.new do |io|
message = io.read_nonblock 5000
@selector.register io, :w
Fiber.yield
io.write_nonblock response(message)
io.close
@fibers.delete io
end
end
def response(message)
<<~RESP
HTTP/1.1 200 OK
<html>
<body>
<h1>こんにちは 世界</h1>
<p>HTTPを使って通信するサーバーを作ったよ。</p>
<p>#{message}</p>
</body>
</html>
RESP
end
end
end
s = FiberServer::Server.new
s.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.