Class: Async::WebSocket::Connection
- Inherits:
-
Object
- Object
- Async::WebSocket::Connection
- Defined in:
- lib/async/websocket/connection.rb
Overview
This is a basic synchronous websocket client:
Constant Summary collapse
- BLOCK_SIZE =
Async::IO::Stream::BLOCK_SIZE
- EVENTS =
[:open, :message, :close]
Instance Attribute Summary collapse
-
#driver ⇒ Object
readonly
Returns the value of attribute driver.
-
#url ⇒ Object
readonly
Returns the value of attribute url.
Instance Method Summary collapse
- #close ⇒ Object
-
#initialize(socket, driver) ⇒ Connection
constructor
A new instance of Connection.
- #next_event ⇒ Object
- #next_message ⇒ Object
- #send_message(message) ⇒ Object
- #send_text(text) ⇒ Object
- #write(data) ⇒ Object
Constructor Details
#initialize(socket, driver) ⇒ Connection
Returns a new instance of Connection.
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/async/websocket/connection.rb', line 34 def initialize(socket, driver) @socket = socket @driver = driver @queue = [] @driver.on(:error) do |error| raise error end EVENTS.each do |event| @driver.on(event) do |data| @queue.push(data) end end @driver.start end |
Instance Attribute Details
#driver ⇒ Object (readonly)
Returns the value of attribute driver.
53 54 55 |
# File 'lib/async/websocket/connection.rb', line 53 def driver @driver end |
#url ⇒ Object (readonly)
Returns the value of attribute url.
54 55 56 |
# File 'lib/async/websocket/connection.rb', line 54 def url @url end |
Instance Method Details
#close ⇒ Object
96 97 98 99 |
# File 'lib/async/websocket/connection.rb', line 96 def close @driver.close @socket.close end |
#next_event ⇒ Object
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/async/websocket/connection.rb', line 56 def next_event @socket.flush while @queue.empty? data = @socket.readpartial(BLOCK_SIZE) if data and !data.empty? @driver.parse(data) else return nil end end @queue.shift rescue EOFError, Errno::ECONNRESET return nil end |
#next_message ⇒ Object
74 75 76 77 78 79 80 81 82 |
# File 'lib/async/websocket/connection.rb', line 74 def while event = next_event if event.is_a? ::WebSocket::Driver::MessageEvent return JSON.parse(event.data) elsif event.is_a? ::WebSocket::Driver::CloseEvent return nil end end end |
#send_message(message) ⇒ Object
88 89 90 |
# File 'lib/async/websocket/connection.rb', line 88 def () @driver.text(JSON.dump()) end |
#send_text(text) ⇒ Object
84 85 86 |
# File 'lib/async/websocket/connection.rb', line 84 def send_text(text) @driver.text(text) end |
#write(data) ⇒ Object
92 93 94 |
# File 'lib/async/websocket/connection.rb', line 92 def write(data) @socket.write(data) end |