Skip to content

Instantly share code, notes, and snippets.

@jhsu
Created February 11, 2012 03:22
Show Gist options
  • Save jhsu/1795722 to your computer and use it in GitHub Desktop.
Save jhsu/1795722 to your computer and use it in GitHub Desktop.
WebSocket and Socket
source :rubygems
gem "redis"
gem "em-websocket"
gem "web-socket-ruby", :require => "web_socket"
GEM
remote: http://rubygems.org/
specs:
addressable (2.2.6)
em-websocket (0.3.6)
addressable (>= 2.1.1)
eventmachine (>= 0.12.9)
eventmachine (0.12.10)
redis (2.2.2)
web-socket-ruby (0.1.0)
PLATFORMS
ruby
DEPENDENCIES
em-websocket
redis
web-socket-ruby
app: ruby socket.rb $PORT
# Simple socket to websocket example
# Run this file `ruby socket.rb`, this starts a websocket server and listens on port 2000
# start a websocket client,
# for example the stdio client from https://github.com/gimite/web-socket-ruby/blob/master/samples/stdio_client.rb
# connect on telnet `telnet localhost 2000`, type some messages to see it broadcasted to websocket clients!
# - or -
# tail -f ./logs/development.log | nc localhost 2000 -
require 'bundler'
Bundler.require
require 'socket'
require 'json'
uri = URI.parse(ENV["REDISTOGO_URL"] || "localhost:6379")
REDIS = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
threads = []
@channel = EM::Channel.new
threads << Thread.new do
while line = REDIS.blpop("cyclops:messages", 10)
puts line
begin
JSON line
@channel.push(line)
rescue JSON::ParserError
end
end
end
threads << Thread.new do
EventMachine.run {
EventMachine::WebSocket.start(:host => "localhost", :port => ARGV.first || ENV['PORT']) do |ws|
ws.onopen {
puts "WebSocket connection open"
sid = @channel.subscribe {|msg| ws.send msg }
ws.onclose { @channel.unsubscribe(sid) }
ws.onmessage {|msg| }
}
end
}
end
threads.map(&:join)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment