Created
October 9, 2014 05:39
-
-
Save roder/ab211f2f58ad6c90a3a9 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' | |
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 = { | |
:type => "command", | |
:to => 1, | |
:timeout => 10000, | |
:command => "led.on" | |
} | |
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", 1234) | |
trap("INT") { supervisor.terminate; exit } | |
sleep |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment