Created
June 29, 2012 00:03
-
-
Save hannahwhy/3014842 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 'celluloid/io' | |
class EchoServer | |
include Celluloid::IO | |
def initialize(host, port) | |
@server = TCPServer.new(host, port) | |
run! | |
end | |
def run | |
loop { handle_connection!(@server.accept) } | |
end | |
def handle_connection(socket) | |
loop do | |
socket.write socket.readpartial(4096) | |
sleep 1 | |
end | |
end | |
end | |
class HiEchoClient | |
include Celluloid::IO | |
def initialize(host, port) | |
@socket = TCPSocket.new(host, port) | |
run! | |
end | |
def msg | |
'hi' | |
end | |
def run | |
loop do | |
@socket.write(msg) | |
puts @socket.readpartial(4096) | |
end | |
end | |
end | |
class ByeEchoClient < HiEchoClient | |
def msg | |
'bye' | |
end | |
end | |
host = '127.0.0.1' | |
port = 1234 | |
server = EchoServer.new(host, port) | |
c1 = HiEchoClient.new(host, port) | |
c2 = ByeEchoClient.new(host, port) | |
trap('INT') do | |
[server, c1, c2].each(&:terminate) | |
exit | |
end | |
sleep |
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 'celluloid/io' | |
class EchoServer | |
include Celluloid::IO | |
def initialize(host, port) | |
@server = TCPServer.new(host, port) | |
run! | |
end | |
def run | |
loop { handle_connection!(@server.accept) } | |
end | |
def handle_connection(socket) | |
loop do | |
socket.write socket.readpartial(4096) | |
sleep 1 | |
end | |
end | |
end | |
class HiEchoClient | |
include Celluloid::IO | |
def self.inherited(sub) | |
sub.send(:include, Celluloid::IO) | |
end | |
def initialize(host, port) | |
@socket = TCPSocket.new(host, port) | |
run! | |
end | |
def msg | |
'hi' | |
end | |
def run | |
loop do | |
@socket.write(msg) | |
puts @socket.readpartial(4096) | |
end | |
end | |
end | |
class ByeEchoClient < HiEchoClient | |
def msg | |
'bye' | |
end | |
end | |
host = '127.0.0.1' | |
port = 1234 | |
server = EchoServer.new(host, port) | |
c1 = HiEchoClient.new(host, port) | |
c2 = ByeEchoClient.new(host, port) | |
trap('INT') do | |
[server, c1, c2].each(&:terminate) | |
exit | |
end | |
sleep |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For those coming from elsewhere, this gist is an example for celluloid/celluloid-io#22.