Class: FTW::WebSocket::Writer

Inherits:
Object
  • Object
show all
Extended by:
Singleton
Includes:
Constants
Defined in:
lib/ftw/websocket/writer.rb

Overview

This class implements a writer for WebSocket messages over a stream.

Protocol diagram copied from RFC6455 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-------+-+-------------+-------------------------------+ |F|R|R|R| opcode|M| Payload len | Extended payload length | |I|S|S|S| (4) |A| (7) | (16/64) | |N|V|V|V| |S| | (if payload len==126/127) | | |1|2|3| |K| | | +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + | Extended payload length continued, if payload len == 127 |

                                • -------------------------------

| |Masking-key, if MASK set to 1 | +-------------------------------+-------------------------------+ | Masking-key (continued) | Payload Data | +-------------------------------- - - - - - - - - - - - - - - - + : Payload Data continued ... :

+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
|                     Payload Data continued ...                |
+---------------------------------------------------------------+

Constant Summary collapse

VALID_MODES =

A list of valid modes. Used to validate input in #write_text.

In :server mode, payloads are not masked. In :client mode, payloads are masked. Masking is described in RFC6455.

[:server, :client]

Constants included from Constants

Constants::OPCODE_BINARY, Constants::OPCODE_CLOSE, Constants::OPCODE_CONTINUATION, Constants::OPCODE_PING, Constants::OPCODE_PONG, Constants::OPCODE_TEXT, Constants::WEBSOCKET_ACCEPT_UUID

Instance Method Summary collapse

Methods included from Singleton

included, singleton

Instance Method Details

#write_text(connection, text, mode = :server) ⇒ Object

Write the given text in a websocket frame to the connection.

Valid 'mode' settings are :server or :client. If :client, the payload will be masked according to RFC6455 section 5.3: http://tools.ietf.org/html/rfc6455#section-5.3



45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/ftw/websocket/writer.rb', line 45

def write_text(connection, text, mode=:server)
  if !VALID_MODES.include?(mode)
    raise InvalidArgument.new("Invalid message mode: #{mode}, expected one of" \
                              "#{VALID_MODES.inspect}")
  end

  data = []
  pack = []

  # For now, assume single-fragment, text frames
  pack_opcode(data, pack, OPCODE_TEXT)
  pack_payload(data, pack, text, mode)
  connection.write(data.pack(pack.join("")))
end