Class: Sanford::Protocol::Connection
- Inherits:
-
Object
- Object
- Sanford::Protocol::Connection
- Includes:
- Sanford::Protocol
- Defined in:
- lib/sanford-protocol/connection.rb
Overview
Sanford Protocol’s connection class wraps a socket and provides a ‘read` and `write` method for using Sanford’s message protocol. Mixes in the protocol to get the ‘msg_version`, `msg_size`, and `msg_body` handler methods.
Constant Summary
Constants included from Sanford::Protocol
Instance Method Summary collapse
- #close ⇒ Object
- #close_write ⇒ Object
-
#initialize(tcp_socket) ⇒ Connection
constructor
A new instance of Connection.
- #peek(timeout = nil) ⇒ Object
-
#read(timeout = nil) ⇒ Object
Message format (see sanford-protocal.rb): |—— 1B ——-|—— 4B ——-|– (msg body size)B –| | (packed header) | (packed header) | (BSON binary string) | | msg version | msg body size | msg body | |—————–|—————–|———————-|.
- #write(data) ⇒ Object
Methods included from Sanford::Protocol
#msg_body, #msg_size, #msg_version
Constructor Details
#initialize(tcp_socket) ⇒ Connection
Returns a new instance of Connection.
14 15 16 |
# File 'lib/sanford-protocol/connection.rb', line 14 def initialize(tcp_socket) @socket = Socket.new(tcp_socket) end |
Instance Method Details
#close ⇒ Object
43 44 45 |
# File 'lib/sanford-protocol/connection.rb', line 43 def close @socket.close end |
#close_write ⇒ Object
47 48 49 |
# File 'lib/sanford-protocol/connection.rb', line 47 def close_write @socket.close_write end |
#peek(timeout = nil) ⇒ Object
38 39 40 41 |
# File 'lib/sanford-protocol/connection.rb', line 38 def peek(timeout = nil) wait_for_data(timeout) if timeout @socket.peek end |
#read(timeout = nil) ⇒ Object
Message format (see sanford-protocal.rb): |—— 1B ——-|—— 4B ——-|– (msg body size)B –| | (packed header) | (packed header) | (BSON binary string) | | msg version | msg body size | msg body | |—————–|—————–|———————-|
24 25 26 27 28 29 |
# File 'lib/sanford-protocol/connection.rb', line 24 def read(timeout = nil) wait_for_data(timeout) if timeout MsgVersion.new{ @socket.read msg_version.bytesize }.validate! size = MsgSize.new{ @socket.decode msg_size, msg_size.bytes }.validate!.value return MsgBody.new{ @socket.decode msg_body, size }.validate!.value end |
#write(data) ⇒ Object
31 32 33 34 35 36 |
# File 'lib/sanford-protocol/connection.rb', line 31 def write(data) body = @socket.encode msg_body, data size = @socket.encode msg_size, body.bytesize @socket.write(msg_version, size, body) end |