This library was created out of my frustrations working with the Ruby's built-in Socket classes when writing Working With Sockets. It provides two functions: 1) A better way of building sockets with the common options that are more configurable/portable, and 2) A built-in way of framing messages in an safe and efficient manner. Nothing fancy.
socket = RocketSocket::Build.host('0.0.0.0').port(8080).ssl.read_timeout(60).write_timeout(10).listen(512).tcp
socket.write_timeout #=> 10
socket.host #=> '0.0.0.0'
socket.write('message')
Under the hood this builds up a chain of options that doesn't gets lazily evauluated. At any point you can call #socket to get back something that you can actually call #read
and #write
on, or you can just use the object you get back from the Build
method and it will delegate the method calls to the underlying socket.
Potential alternate syntax...
socket = RocketSocket::Build(host: '0.0.0.0', port: 8080, ssl: true, read_timeout: 60, write_timeout: 10, tcp: true)
socket.write_timeout #=> 10
socket.host #=> '0.0.0.0'
socket.write('message')
This is a module that can be mixed in to any Socket-like object. This includes Ruby's built-in socket classes or an object returned from RocketSocket::Build
.
socket = TCPSocket.new('127.0.0.1', 8080)
socket.extend RocketSocket::Messaging
socket.write_msg 'This will be sent as a single message with proper boundaries, rather than as a stream of data'
The other end of the connection could use a RocketSocket and receive the message like so:
socket = RocketSocket::Build.host('127.0.0.1').port(8080).accept_loop do |connection|
connection.extend RocketSocket::Messaging
connection.read_msg
end