Last active
December 16, 2015 11:39
-
-
Save jeremyd/5429279 to your computer and use it in GitHub Desktop.
Websocket Client Test
This file contains hidden or 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 'websocket/protocol' | |
require 'celluloid' | |
require 'celluloid/io' | |
module Celluloid | |
module IO | |
class TCPSocket | |
#include ConnectionMixin | |
#include RequestMixin | |
def url | |
"http://localhost:9123/timeinfo" | |
end | |
end | |
end | |
end | |
class MozWeb | |
include Celluloid::IO | |
include Celluloid::Logger | |
def initialize | |
s = Celluloid::IO::TCPSocket.new('0.0.0.0', '9123') | |
handler = WebSocket::Protocol.client(s) | |
handler.onmessage { |message| puts "never gets here" } | |
handler.onopen { |message| puts "open" } | |
handler.onclose { |message| puts "close" } | |
handler.start | |
end | |
end | |
MozWeb.supervise_as(:mozweb) | |
sleep |
This file contains hidden or 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 'reel' | |
MYAPP_IP = "0.0.0.0" | |
MYAPP_PORT = "9123" | |
class TimeClient | |
include Celluloid | |
include Celluloid::Notifications | |
include Celluloid::Logger | |
def initialize(websocket) | |
info "Streaming json_world_view changes to client" | |
@socket = websocket | |
subscribe('time_change', :notify_time_change) | |
every(1) { publish 'time_change', "asdfasdfasdfasdfhi" } | |
end | |
def notify_time_change(topic, new_time) | |
@socket << new_time | |
rescue Reel::SocketError | |
info "Time client disconnected" | |
terminate | |
end | |
end | |
class WebServer < Reel::Server | |
include Celluloid::Logger | |
def initialize(host = "0.0.0.0", port = 9123) | |
super(host, port, &method(:on_connection)) | |
end | |
def on_connection(connection) | |
while request = connection.request | |
case request | |
when Reel::Request | |
info "Received a *normal request" | |
when Reel::WebSocket | |
info "Received a WebSocket connection" | |
route_websocket request | |
end | |
end | |
end | |
def route_websocket(socket) | |
if socket.url == "/timeinfo" | |
TimeClient.new(socket) | |
else | |
info "Received invalid WebSocket request for: #{socket.url}" | |
socket.close | |
end | |
end | |
end | |
WebServer.supervise_as(:webserver) | |
sleep |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment