Skip to content

Instantly share code, notes, and snippets.

@jcalvert
Last active December 15, 2015 02:15
Show Gist options
  • Save jcalvert/f015be8e0ec41e92e638 to your computer and use it in GitHub Desktop.
Save jcalvert/f015be8e0ec41e92e638 to your computer and use it in GitHub Desktop.
celluloid tcp client
require 'celluloid/current'
require 'celluloid/io'
class MyClient
include Celluloid::IO
finalizer :close_connection
def initialize(channel_id, host, port)
raise ArgumentError.new("Valid host and port required!") unless !host.nil? && !port.nil?
@channel_id = channel_id
@buffer = String.new
@host = host
@port = port
async.run!
end
def write_data(payload)
socket.write payload
end
def run!
loop do
begin
@buffer << socket.readpartial(4096)
process_messages
rescue EOFError => eof
close_connection
raise StandardError.new("Connection was closed from the other side.")
end
end
end
def process_messages
p "Hey, #{@buffer}"
end
def close_connection
puts "Closing connection on finalization"
@socket.close unless @socket.nil?
end
private
def socket
@socket ||= TCPSocket.new(@host, @port)
end
end
# in shell `nc -l -v -k 12345`
actor = MyClient.supervise as: "foo", args: ["foo", "localhost", 12345]
Celluloid::Actor[:foo].write_data "foobar"
# data echos in netcat window, now kill process
Celluloid::Actor[:foo].dead?
NoMethodError: undefined method `dead?' for nil:NilClass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment