Last active
August 29, 2015 13:56
-
-
Save dasibre/8959399 to your computer and use it in GitHub Desktop.
Ruby I/O
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
| class IOLoop | |
| # List of streams that this IO loop will handle. | |
| attr_reader :streams | |
| def initialize | |
| @streams = [] | |
| end | |
| # Low-level API for adding a stream. | |
| def <<(stream) | |
| @streams << stream | |
| stream.on(:close) do | |
| @streams.delete(stream) | |
| end | |
| end | |
| # Some useful helpers: | |
| def io(io) | |
| stream = Stream.new(io) | |
| self << stream | |
| stream | |
| end | |
| def open(file, *args) | |
| io File.open(file, *args) | |
| end | |
| def connect(host, port) | |
| io TCPSocket.new(host, port) | |
| end | |
| def listen(host, port) | |
| server = Server.new(TCPServer.new(host, port)) | |
| self << server | |
| server.on(:accept) do |stream| | |
| self << stream | |
| end | |
| server | |
| end | |
| # Start the loop by calling #tick over and over again. | |
| def start | |
| @running = true | |
| tick while @running | |
| end | |
| # Stop/pause the event loop after the current tick. | |
| def stop | |
| @running = false | |
| end | |
| def tick | |
| @streams.each do |stream| | |
| stream.handle_read if stream.readable? | |
| stream.handle_write if stream.writable? | |
| end | |
| end | |
| end | |
| #usage | |
| l = IOLoop.new | |
| ruby = i.connect('ruby-lang.org', 80) # 1 | |
| ruby << "GET / HTTP/1.0\r\n\r\n" # 2 | |
| # Print output | |
| ruby.on(:data) do |chunk| | |
| puts chunk # 3 | |
| end | |
| # Stop IO loop when we're done | |
| ruby.on(:close) do | |
| l.stop # 4 | |
| end | |
| l.start # 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment