Skip to content

Instantly share code, notes, and snippets.

@roder
Created October 11, 2014 04:26
Show Gist options
  • Save roder/a9ecb12059616c6f9ed7 to your computer and use it in GitHub Desktop.
Save roder/a9ecb12059616c6f9ed7 to your computer and use it in GitHub Desktop.
require 'celluloid/io'
require 'json'
# require 'celluloid/autostart'
class TestServer
include Celluloid::IO
finalizer :shutdown
def initialize(host, port)
puts "*** Starting echo server on #{host}:#{port}"
# Since we included Celluloid::IO, we're actually making a
# Celluloid::IO::TCPServer here
@server = TCPServer.new(host, port)
async.run
end
def shutdown
@server.close if @server
end
def run
loop { async.handle_connection @server.accept }
end
def handle_connection(socket)
_, port, host = socket.peeraddr
puts "*** Received connection from #{host}:#{port}"
# loop { socket.write socket.readpartial(4096) }
# This is just a test, followed this format:
# https://github.com/soldair/pinoccio-server/blob/master/troop.js#L163
cmd = {
:to => 1,
:command => "hq.print(\"ack\")",
:id => 1,
:timeout => 10000,
:type => "command",
}
json_cmd = cmd.to_json + "\n"
socket.write json_cmd # The light never turns on. Why?
puts json_cmd
loop {
puts socket.readpartial(4096)
}
rescue EOFError
puts "*** #{host}:#{port} disconnected"
socket.close
end
end
supervisor = TestServer.supervise("0.0.0.0", 22756)
trap("INT") { supervisor.terminate; exit }
sleep
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment