Skip to content

Instantly share code, notes, and snippets.

@hannahwhy
Created June 29, 2012 00:03
Show Gist options
  • Save hannahwhy/3014842 to your computer and use it in GitHub Desktop.
Save hannahwhy/3014842 to your computer and use it in GitHub Desktop.
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
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
@hannahwhy
Copy link
Author

For those coming from elsewhere, this gist is an example for celluloid/celluloid-io#22.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment