The server.rb
file slowly feeds data to the socket, and both clients will yield data as it's available. UneventfulMachine
steals the API of EventMachine.
Created
January 27, 2014 22:16
-
-
Save tenderlove/8658454 to your computer and use it in GitHub Desktop.
This file contains 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
require 'eventmachine' | |
EventMachine.run do | |
EventMachine.connect '127.0.0.1', 28561 do |c| | |
def c.receive_data(data) | |
p data | |
end | |
end | |
end |
This file contains 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
require 'socket' | |
class GenericServer | |
def initialize addr, port, size | |
@size = size | |
@serv = TCPServer.new '127.0.0.1', 28561 | |
end | |
def start(&blk) | |
@size.times.map { | |
Thread.new { | |
while s = @serv.accept | |
blk.call s | |
end | |
} | |
}.each(&:join) | |
end | |
end | |
server = GenericServer.new('127.0.0.1', 28561, 5) | |
server.start do |socket| | |
socket.print "HTTP/1.1 200 OK\r\n" | |
socket.print "Content-Type: text/html\r\n" | |
socket.print "Connection: close\r\n" | |
socket.print "\r\n\r\n" | |
"Hello World!\n".bytes.each do |byte| | |
sleep 0.1 | |
socket.putc byte | |
end | |
socket.close | |
end |
This file contains 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
require 'socket' | |
class UneventfulMachine | |
@sockets = {} | |
def self.run | |
yield | |
maxlen = 1024 | |
loop do | |
break if @sockets.empty? | |
rds, = IO.select @sockets.keys | |
rds.each do |io| | |
data = io.read_nonblock maxlen, exception: false | |
case data | |
when :wait_readable | |
when nil; @sockets.delete io | |
else | |
@sockets[io].receive_data data | |
end | |
end | |
end | |
end | |
def self.connect host, port, object = nil | |
case object | |
when nil | |
object = Object.new | |
yield object | |
when Module | |
object = Object.new.extend(object) | |
end | |
io = TCPSocket.new host, port | |
@sockets[io] = object | |
end | |
end | |
module Echo | |
def receive_data(data) | |
p data | |
end | |
end | |
UneventfulMachine.run do | |
UneventfulMachine.connect '127.0.0.1', 28561 do |c| | |
def c.receive_data(data) | |
p data | |
end | |
end | |
UneventfulMachine.connect '127.0.0.1', 28561, Echo | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment