lib/ftw/websocket.rb in ftw-0.0.8 vs lib/ftw/websocket.rb in ftw-0.0.9

- old
+ new

@@ -36,10 +36,11 @@ def initialize(request) @key_nonce = generate_key_nonce @request = request prepare(@request) @parser = FTW::WebSocket::Parser.new + @messages = [] end # def initialize # Set the connection for this websocket. This is usually invoked by FTW::Agent # after the websocket upgrade and handshake have been successful. # @@ -116,23 +117,35 @@ # Iterate over each WebSocket message. This method will run forever unless you # break from it. # # The text payload of each message will be yielded to the block. def each(&block) - loop do - @parser.feed(@connection.read(16384)) do |payload| - yield payload - end + while true + block.call(receive) end end # def each + # Receive a single payload + def receive + @messages += network_consume if @messages.empty? + @messages.shift + end # def receive + + # Consume payloads from the network. + def network_consume + payloads = [] + @parser.feed(@connection.read(16384)) do |payload| + payloads << payload + end + return payloads + end # def network_consume + # Publish a message text. # # This will send a websocket text frame over the connection. def publish(message) writer = FTW::WebSocket::Writer.singleton writer.write_text(@connection, message) end # def publish - public(:initialize, :connection=, :handshake_ok?, :each, :publish) + public(:initialize, :connection=, :handshake_ok?, :each, :publish, :receive) end # class FTW::WebSocket -