Class: Plushie::Transport::TCPAdapter
- Inherits:
-
Object
- Object
- Plushie::Transport::TCPAdapter
- Defined in:
- lib/plushie/transport/tcp_adapter.rb
Overview
Example iostream adapter for TCP sockets.
Reads from a TCP socket in a background thread, decodes length-prefixed frames, and forwards complete messages to the Connection. Outbound data is framed and written to the socket.
Usage: socket = TCPSocket.new("localhost", 4000) adapter = Transport::TCPAdapter.new(socket) conn = Connection.iostream(adapter: adapter, format: :msgpack)
Instance Method Summary collapse
-
#initialize(socket) ⇒ TCPAdapter
constructor
A new instance of TCPAdapter.
-
#on_bridge(connection) ⇒ Object
Called by the Connection during iostream setup.
-
#send_data(data) ⇒ Object
Called by the Connection to write data to the transport.
-
#stop ⇒ Object
Stop the adapter and close the socket.
Constructor Details
#initialize(socket) ⇒ TCPAdapter
Returns a new instance of TCPAdapter.
20 21 22 23 24 25 26 27 28 29 |
# File 'lib/plushie/transport/tcp_adapter.rb', line 20 def initialize(socket) @socket = socket @connection = nil @reader = nil # Disable Nagle's algorithm for low-latency protocol messages. if socket.respond_to?(:setsockopt) socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1) end end |
Instance Method Details
#on_bridge(connection) ⇒ Object
Called by the Connection during iostream setup. Stores the connection reference and starts the reader thread.
35 36 37 38 39 |
# File 'lib/plushie/transport/tcp_adapter.rb', line 35 def on_bridge(connection) @connection = connection @reader = Thread.new { read_loop } @reader.name = "plushie-tcp-reader" end |
#send_data(data) ⇒ Object
Called by the Connection to write data to the transport. Wraps data in a length-prefixed frame before writing.
45 46 47 48 49 |
# File 'lib/plushie/transport/tcp_adapter.rb', line 45 def send_data(data) framed = Framing.encode_packet(data) @socket.write(framed) @socket.flush end |
#stop ⇒ Object
Stop the adapter and close the socket.
52 53 54 55 56 57 58 59 |
# File 'lib/plushie/transport/tcp_adapter.rb', line 52 def stop @reader&.kill begin @socket&.close rescue IOError nil end end |