Created
February 12, 2014 16:43
-
-
Save dasibre/8959376 to your computer and use it in GitHub Desktop.
Network I/O ruby Event handling chat server
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
| #event loop demystified ruby | |
| #Working with network I/O in Ruby is so easy: | |
| #https://practicingruby.com/articles/event-loops-demystified | |
| require 'socket' | |
| # Start a server on port 9234 | |
| server = TCPServer.new('0.0.0.0', 9234) | |
| # Wait for incoming connections | |
| while io = server.accept | |
| io << "HTTP/1.1 200 OK\r\n\r\nHello world!" | |
| io.close | |
| end | |
| #chat server | |
| class ChatServer | |
| def initialize | |
| @clients = [] | |
| @client_id = 0 | |
| end | |
| def <<(server) | |
| server.on(:accept) do |stream| | |
| add_client(stream) | |
| end | |
| end | |
| def add_client(stream) | |
| id = (@client_id += 1) | |
| send("User ##{id} joined\n") | |
| stream.on(:data) do |chunk| | |
| send("User ##{id} said: #{chunk}") | |
| end | |
| stream.on(:close) do | |
| @clients.delete(stream) | |
| send("User ##{id} left") | |
| end | |
| @clients << stream | |
| end | |
| def send(msg) | |
| @clients.each do |stream| | |
| stream << msg | |
| end | |
| end | |
| end | |
| # usage | |
| io = IOLoop.new | |
| server = ChatServer.new | |
| server << io.listen('0.0.0.0', 1234) | |
| io.start | |
| #Test Script | |
| # from User #1's console: | |
| $ telnet 127.0.0.1 1234 | |
| User #2 joined | |
| User #2 said: Hi | |
| Hi | |
| User #1 said: Hi | |
| User #2 said: Bye | |
| User #2 left | |
| # from User #2's console (quits after saying Bye) | |
| $ telnet 127.0.0.1 1234 | |
| User #1 said: Hi | |
| Bye | |
| User #2 said: Bye | |
| #Event Handling | |
| module EventEmitter | |
| def _callbacks | |
| @_callbacks ||= Hash.new { |h, k| h[k] = [] } | |
| end | |
| def on(type, &blk) | |
| _callbacks[type] << blk | |
| self | |
| end | |
| def emit(type, *args) | |
| _callbacks[type].each do |blk| | |
| blk.call(*args) | |
| end | |
| end | |
| end | |
| class HTTPServer | |
| include EventEmitter | |
| end | |
| server = HTTPServer.new | |
| server.on(:request) do |req, res| | |
| res.respond(200, 'Content-Type' => 'text/html') | |
| res << "Hello world!" | |
| res.close | |
| end | |
| # When a new request comes in, the server will run: | |
| # server.emit(:request, req, res) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment