Class: Tubesock
- Inherits:
-
Object
- Object
- Tubesock
- Defined in:
- lib/tubesock.rb,
lib/tubesock/version.rb
Overview
Easily interact with WebSocket connections over Rack. TODO: Example with pure Rack
Defined Under Namespace
Modules: Hijack
Constant Summary collapse
- HijackNotAvailable =
Class.new RuntimeError
- VERSION =
"0.2.5"
Class Method Summary collapse
Instance Method Summary collapse
- #close ⇒ Object
- #closed? ⇒ Boolean
-
#initialize(socket, version) ⇒ Tubesock
constructor
A new instance of Tubesock.
- #keepalive ⇒ Object
- #listen ⇒ Object
- #onclose(&block) ⇒ Object
- #onmessage(&block) ⇒ Object
- #onopen(&block) ⇒ Object
- #send_data(data, type = :text) ⇒ Object
Constructor Details
#initialize(socket, version) ⇒ Tubesock
Returns a new instance of Tubesock.
10 11 12 13 14 15 16 17 |
# File 'lib/tubesock.rb', line 10 def initialize(socket, version) @socket = socket @version = version @open_handlers = [] = [] @close_handlers = [] end |
Class Method Details
.hijack(env) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/tubesock.rb', line 19 def self.hijack(env) if env['rack.hijack'] env['rack.hijack'].call socket = env['rack.hijack_io'] handshake = WebSocket::Handshake::Server.new handshake.from_rack env socket.write handshake.to_s self.new socket, handshake.version else raise Tubesock::HijackNotAvailable end end |
Instance Method Details
#close ⇒ Object
70 71 72 73 74 75 76 77 |
# File 'lib/tubesock.rb', line 70 def close @close_handlers.each(&:call) if @socket.respond_to?(:closed?) @socket.close unless @socket.closed? else @socket.close end end |
#closed? ⇒ Boolean
79 80 81 |
# File 'lib/tubesock.rb', line 79 def closed? @socket.closed? end |
#keepalive ⇒ Object
83 84 85 86 87 88 89 90 91 92 93 94 95 |
# File 'lib/tubesock.rb', line 83 def keepalive thread = Thread.new do Thread.current.abort_on_exception = true loop do sleep 5 send_data nil, :ping end end onclose do thread.kill end end |
#listen ⇒ Object
58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/tubesock.rb', line 58 def listen keepalive Thread.new do Thread.current.abort_on_exception = true @open_handlers.each(&:call) each_frame do |data| .each{|h| h.call(data) } end close end end |
#onclose(&block) ⇒ Object
54 55 56 |
# File 'lib/tubesock.rb', line 54 def onclose(&block) @close_handlers << block end |
#onmessage(&block) ⇒ Object
50 51 52 |
# File 'lib/tubesock.rb', line 50 def (&block) << block end |
#onopen(&block) ⇒ Object
46 47 48 |
# File 'lib/tubesock.rb', line 46 def onopen(&block) @open_handlers << block end |
#send_data(data, type = :text) ⇒ Object
35 36 37 38 39 40 41 42 43 44 |
# File 'lib/tubesock.rb', line 35 def send_data data, type = :text frame = WebSocket::Frame::Outgoing::Server.new( version: @version, data: data, type: type ) @socket.write frame.to_s rescue IOError, Errno::EPIPE close end |