Created
October 8, 2014 06:48
-
-
Save roder/09468f3135660fe942e8 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" | |
} | |
loop { | |
puts socket.readpartial(4096) | |
socket.write cmd.to_json # The light never turns on. Why? | |
} | |
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
i think you might be missing a newline after your json command?
i have to study up a little on ruby tcp to help more. hey you should really make a repository just for your rb server!